<?php
/**
 * Created by PhpStorm.
 * User: g
 * Date: 2018/3/14
 * Time: 13:08
 */

namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use think\Validate;
use app\index\validate\Valid;

class Mobile extends Controller
{

    public function _initialize(Request $request = null)
    {
        header('Access-Control-Allow-Origin:*');
    }
    public function testuse(){
        $post = $GLOBALS['HTTP_RAW_POST_DATA'];
        db("test_abs")->insert(["txt"=>$post]);
        return json_encode(['status'=>true,'message'=>'操作成功']);
    }
    public function testuse1(){
        $post = $GLOBALS['HTTP_RAW_POST_DATA'];
        db("test_abs")->insert(["txt"=>$post]);
        $data["status"]=true;
        $data["message"]="";
        $data["data"]=["RwdId"=>rand(100000,1000000)];
         return json_encode($data);
    }
    public function testuse2(){
        $post = $GLOBALS['HTTP_RAW_POST_DATA'];
        db("test_abs")->insert(["txt"=>$post]);
        $arr["status"]=true;
        $arr["message"]="操作成功";
        $arr["data"]=["PrimaryKey"=>123,"result"=>"通过","message"=>"成功通过"];
        return json_encode($arr);
    }
     //查看流程图
    public function workflowchart(){
        $ywid = $this->request->param('id');
        $ywtype=$this->request->param('type');
        $userid=$this->request->param('userid');
        $em_id = db('users')->where('login_name',$userid)->value('employee_id');
        $user = Db::table('users')->where('login_name',$userid)->find();
            $post_data = array(
                'loginName' => $user["login_name"],
                'password' => $user["login_pwd"],
                'tenantCode' => ''
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,            config('workflow_url')."/horizon/workflow/rest/user/login.wf" );
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt($ch, CURLOPT_POST,           1 );
            curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($post_data));// 必须为字符串
            curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain'));// 必须声明请求头
            $return = curl_exec($ch);

            $return = json_decode($return);
//
            if($return->success==true){
//
                Session::set("accessToken",$return->data->accessToken);
//
            }

        $workId = db('cg_workflow')->where(['ywlx'=>$ywtype,'yw_id'=>$ywid])->value('workId');
        $trackId = db('cg_workflow')->where(['ywlx'=>$ywtype,'yw_id'=>$ywid])->value('trackId');//dump($workId);dump($trackId);
        //echo config('workflow_url').'/horizon/workflow/module/workflow/flowchart.jsp?workId='.$workId.
          //  '&trackId='.$trackId;die;
       // header('location:'.config('workflow_url').'/horizon/workflow/module/workflow/flowchart.jsp?workId='.$workId.
        //    '&trackId='.$trackId);
        if($workId&&$trackId)
            $url=config('workflow_url').'/workflow/module/workflow/flow.info.html?workId='.$workId.'&trackId='.$trackId;
        else
            $url="";
        return json_encode(["url"=>$url]);
    }
    /**
     * 登录
     */
    public function login(){
        $userid = $this->request->param('userid');
        $em_id = db('users')->where('login_name',$userid)->value('employee_id');
        session('employee_id',$em_id);
        if($userid&&$em_id){

            $user = Db::table('users')->where('login_name',$userid)->find();
            $post_data = array(
                'loginName' => $user["login_name"],
                'password' => $user["login_pwd"],
                'tenantCode' => ''
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,            config('workflow_url')."/horizon/workflow/rest/user/login.wf" );
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt($ch, CURLOPT_POST,           1 );
            curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($post_data));// 必须为字符串
            curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain'));// 必须声明请求头
            $return = curl_exec($ch);

            $return = json_decode($return);
//
            if($return->success==true){
//
                Session::set("accessToken",$return->data->accessToken);
//
            }

            echo json_encode(['success'=>true,'msg'=>'登录成功']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'请提供正确的参数']);
        }
    }

    /**
     * 手机端api ---上班打卡
     */
    public function index(){
        //打开
        $data = [];
        $data['sbdd'] = $this->request->post('sbdd');
        $data['sbzp'] = $this->request->post('sbzp');
        $data['sbsm'] = $this->request->post('sbsm');
        $data['sbsj'] = date('H:i:s');
        $data['date'] = date('Y-m-d');
        $data['em_id'] = session('employee_id');
        $data['em_sn'] = db('employee')->where('id',session('employee_id'))->value('em_no');
        $data['em_name'] = db('employee')->where('id',session('employee_id'))->value('em_name');
        $data['em_de'] = db('department t')->join('department_employee t2','t.id=t2.department_id')->where('t2.employee_id',session('employee_id'))->value('t.de_name');
        $data['sbjlpc'] = $this->request->post('sbjlpc');
        $data['week'] = date('W');
        $bool = db('yd_kq_log')->insert($data);
        if(false!==$bool)
            echo json_encode(['success'=>1,'msg'=>'操作成功']);
        else
            echo json_encode(['success'=>0,'msg'=>'操作失败']);
    }

    /**
     * 手机端api ---下班打卡
     */
    public function xbdk(){
        //打开
        $data = [];
        $data['xbdd'] = $this->request->post('xbdd');
        $data['xbzp'] = $this->request->post('xbzp');
        $data['xbsm'] = $this->request->post('xbsm');
        $data['xbsj'] = date('H:i:s');
        $data['date'] = date('Y-m-d');
        $data['jlpc'] = $this->request->post('sbjlpc');
        $bool = db('yd_kq_log')->where('date',date('Y-m-d'))->insert($data);
        if(false!==$bool)
            echo json_encode(['success'=>1,'msg'=>'操作成功']);
        else
            echo json_encode(['success'=>0,'msg'=>'操作失败']);
    }

    /**
     * @param $url
     * @param $post_data
     * @return mixed
     */
    public function curl_post($url,$post_data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,            $url );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_POST,           1 );
        curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($post_data));// 必须为字符串
        curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain'));// 必须声明请求头
        $return = curl_exec($ch);
        curl_close($ch);
        return $return = json_decode($return);
    }

    public function curl_get($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,            $url );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $return = curl_exec($ch);
        curl_close($ch);
        return $return;
    }

    //对象转成数组
    function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }
    public function gettoken($userid){
        $em_id = db('users')->where('login_name',$userid)->value('employee_id');
        $user = Db::table('users')->where('login_name',$userid)->find();
            $post_data = array(
                'loginName' => $user["login_name"],
                'password' => $user["login_pwd"],
                'tenantCode' => ''
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,            "http://61.129.51.183:10010/hzwf73/horizon/workflow/rest/user/login.wf" );
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt($ch, CURLOPT_POST,           1 );
            curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($post_data));// 必须为字符串
            curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain'));// 必须声明请求头
            $return = curl_exec($ch);

            $return = json_decode($return);
            if($return->success==true){
//
                return $return->data->accessToken;
//
            }
    }
    /**
     * 手机端api ---待办流程
     */
    public function dblc(){
        $userid = $this->request->param('userid');
        $em_id = db('users')->where('login_name',$userid)->value('employee_id');
        session('employee_id',$em_id);
        if($userid&&$em_id){

            $user = Db::table('users')->where('login_name',$userid)->find();
            $post_data = array(
                'loginName' => $user["login_name"],
                'password' => $user["login_pwd"],
                'tenantCode' => ''
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,            "http://61.129.51.183:10010/hzwf73/horizon/workflow/rest/user/login.wf" );
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt($ch, CURLOPT_POST,           1 );
            curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($post_data));// 必须为字符串
            curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain'));// 必须声明请求头
            $return = curl_exec($ch);

            $return = json_decode($return);
//
            //print_r($return);
            if($return->success==true){
//
                Session::set("accessToken",$return->data->accessToken);
//
            }
        }
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['requestType'] = 'TodoList';
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/todo/page.wf?page='.$page.'&limit=10',$post_data);
        //dump($data);
        if(!$data){
            echo "无工作流";die;
        }
        if(!isset($data->data)||!is_array($data->data)){
            echo '';
        }
        $retdata=[];
        foreach($data->data as $k=>$v){
            $workId = $v->workId;
            $v->myId = db('cg_workflow')->where('workId',$workId)->value('id');
            $v->ywlx = db('cg_workflow')->where(['workId'=>$v->workId])->value('ywlx');
            $v->rwmcjbh = db('cg_workflow')->where(['workId'=>$v->workId])->value('rwmcjbh');
            $v->status = db('cg_workflow')->where(['workId'=>$v->workId])->value('status');
            $v->arrive_time = db('cg_workflow')->where(['workId'=>$v->workId])->value('arrive_time');
            $v->department_id = db('cg_workflow')->where(['workId'=>$v->workId])->value('department_id');
            $v->sqr_id = db('cg_workflow')->where(['workId'=>$v->workId])->value('sqr_id');
            $v->type = db('cg_workflow_ywlx')->where('id',$v->ywlx)->value('title');
            $v->department = db('department')->where('id',$v->department_id)->value('de_name');
            $v->sqr = db('employee')->where('id',$v->sqr_id)->value('em_name');
            $data->data[$k] = $v;
            $retdata[$k]["workId"]=$workId;
            $retdata[$k]["myId"]=$v->myId;
            $retdata[$k]["trackId"]=$v->trackId;
            $retdata[$k]["rwmcjbh"]=$v->rwmcjbh;
            $retdata[$k]["type"]=$v->type;
            $retdata[$k]["type_id"]=$v->ywlx;
            $retdata[$k]["sqr"]=$v->sqr;
            $retdata[$k]["department"]=$v->department;
            $retdata[$k]["sendTime"]=$v->sendTime;
        }
        $data->data = $this->object_array($data->data);
       //print_r($retdata);
        echo json_encode(['data'=>$retdata]);
    }

    //非常规促销费用申请
    public function noformalbacklogdetail(){
        $workId = $this->request->param('workId');
        $trackId = $this->request->param('trackId');
        $myId = $this->request->param('myId');
        //yw_id
        $yw_id =db('cg_workflow')->where('id',$myId)->value('yw_id');

        //打开工作流
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $post_data['trackId'] = $trackId;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post_data);
        $data = object_array($data);

        $info = db('cg_ti')->where('id',$yw_id)->find();
        $info['jxs_name'] = db('cg_jxs')->where('id',$info['jxs_id'])->value('title');
        $info['sqr'] = db('employee')->where('id',$info['cuser'])->value('em_name');
        $info['sqr_job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$info['cuser'])->value('t.job_name');
        $info['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['jxs_type'] = db('cg_jxs_types t')->join('cg_jxs t2','t2.types=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['start'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('start');
        $info['end'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('end');

        if($info['productlat']==1){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'brand'=>['exp','is not null']])->value('brand');
            $info['pro_label'] = '品牌';
            $info['pro_name'] = db('pro_brands')->where('id',$brand_id)->value('brand_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('brand');
        }elseif($info['productlat']==2){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'category'=>['exp','is not null']])->value('category');
            $info['pro_label'] = '品类';
            $info['pro_name'] = db('pro_category')->where('id',$brand_id)->value('category_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('category');
        }elseif($info['productlat']==3){
            $info['pro_label'] = '系列';
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'series'=>['exp','is not null']])->value('series');
            $info['pro_name'] = db('pro_series')->where('id',$brand_id)->value('series_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('series');
        }elseif($info['productlat']==4){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'sku'=>['exp','is not null']])->value('sku');
            $info['pro_label'] = 'sku';
            $info['pro_name'] = db('pro_sku')->where('id',$brand_id)->value('sku_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('sku');
        }elseif($info['productlat']==5){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'product'=>['exp','is not null']])->value('product');
            $info['pro_label'] = '产品';
            $info['pro_name'] = db('pro_products')->where('id',$brand_id)->value('pro_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('product');
        }

        //费用类型
        $info['fylx'] = Db::query('select count(*) cnt from (select feetype from cg_ti_list where ti_id='.$yw_id.' group by feetype) t')[0]['cnt'];
        $info['fylx_name'] = db('cg_ti_list t')->join('cg_feiyongkemu3 t2','t2.id=t.feetype')->where('ti_id',$yw_id)->value('t2.title');
        $info['fye'] = round(db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('yjsjtrfy'),2);
        $info['xl'] = round(db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('totalExpectedSales'),2);
        $info['fyl'] = round($info['fye']/$info['xl']*100,2);
        $gs = db('cg_ti_list')->where(['ti_id'=>$yw_id])->count();
        $yujiroi = db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('yujiroi');
        $info['roi'] = round($yujiroi/$gs,2);

        //查看活动是否重复--判断是否存在费用类型相同收款方也相同的情况
        /*$cnt1 = Db::query('SELECT count(*) cnt from (SELECT gys,count(gys) AS count FROM cg_ti_list where ti_id='.$yw_id.' and gys is not null GROUP BY feetype,payee HAVING count > 1) t');
        $cnt1 = $cnt1[0]['cnt'];

        $info['iscf'] =$cnt1;*/

        /**
         *问题点--start
         */
        $wtd = [];
        //公司建议的TI活动最高费用率值
        $feiYongLv = db('system_param')->where(['t'=>0,'k'=>'feiYongLv'])->value('v');
        if($info['fyl']>$feiYongLv){
            $wtd[] = '本申请单费用率不符合公司规定，公司规定为：'.$feiYongLv.'%';
        }
        //公司建议的TI活动ROI合格值
        $minRoi = db('system_param')->where(['t'=>0,'k'=>'minRoi'])->value('v');
        if($info['roi']<$minRoi){
            $wtd[] = '本申请单ROI不符合公司规定，公司规定合格值为：'.$minRoi.'%';
        }
        //公司建议的TI活动ROI较优值
        $maxRoi = db('system_param')->where(['t'=>0,'k'=>'maxRoi'])->value('v');
        /**
         *问题点--end
         */

        /**
         * 活动列表--start
         */
        $ti_list = db('cg_ti_list')->where('ti_id',$yw_id)->field('start,end,feetype,product,brand,category,series,sku,yjsjtrfy,totalExpectedSales,paymethod')->select();
        foreach($ti_list as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            if($v['product'])
                $v['product_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            elseif($v['brand'])
                $v['product_name'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            elseif($v['category'])
                $v['product_name'] = db('pro_category')->where('id',$v['category'])->value('category_name');
            elseif($v['series'])
                $v['product_name'] = db('pro_series')->where('id',$v['series'])->value('series_name');
            elseif($v['sku'])
                $v['product_name'] = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
            $v['yjfyl'] = round($v['yjsjtrfy']/$v['totalExpectedSales']*100,2);
            $v['zffs'] = db('cg_paymethod')->where('id',$v['paymethod'])->value('title');
            $ti_list[$k] = $v;
        }

        /**
         * 活动列表--end
         */

        //本次申请已耗时
        $time = time()-$info['ctime'];
        $bcsqhs = $this->vtime($time);

        //获取操作记录
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $czjl = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/history.wf',$post_data);
        $czjl = object_array($czjl);
//        echo "<pre>";print_r($czjl);
        foreach($czjl as $k=>$v){
            //查询审批意见
            $wf_id = 0;
//            $v['spyj'] = db('cg_workflow_spyj')->where(['wf_id'=>$wf_id,'spr_id']);
        }

        //查询附件
        $attachs = db('cg_workflow_spyj')->where('wf_id',$myId)->column('attach');
        if($attachs){
            $attach = [];
            foreach($attachs as $item){
                if($item){
                    $item = unserialize($item);
                    foreach($item as $k=>$v){
                        $temp = Db::table('annex')->where(array('id'=>$v))->find();
                        $temp['path'] = '/uploads/'.$temp['path'];
                        $item[$k] = $temp;
                    }
                    $attach = array_merge($attach,$item);
                }
            }

            $this->assign('attach',$attach);

        }
        /**
         * yw_id :业务id
         * data :打开工作流后返回的数据
         * info :ti信息
         * ti_list: ti列表信息
         * czjl:操作记录
         * bcsqhx:本次申请耗时
         * attach:附件
         */
        echo json_encode(['yw_id'=>$yw_id,'data'=>$data->data,'info'=>$info,'ti_list'=>$ti_list,'czjl'=>$czjl,'bcsqhs'=>$bcsqhs,'attach'=>$attach]);

    }

    //工作日报
    public function gzrb(){
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $userid = $this->request->param('userid');
        if($userid)
            $eid=$this->geteid($userid);
        else
            $eid=session('employee_id');
        $data = db('yd_gzrb')->where("em_id=$eid")->order('rq desc')->limit(($page-1)*10,10)->select();
        foreach ($data as $k => $v) {
            # code...
            $data[$k]["lx"]=db("yd_gzrb_lx")->where(["id"=>$v["lx"]])->value("lx");
        }
        echo json_encode(['data'=>$data]);
    }
    //工作日报类型及时间
    public function gzrblx(){
        $data=db("yd_gzrb_lx")->field("id,lx as title")->select();
        echo json_encode(['data'=>$data]);
    }
    //提交工作日报
    public function tjgzrb(){
        $ins = [];
        $ins['rq'] = $this->request->param('rq');
        $ins['lx'] = $this->request->param('lx');
        $ins['nr'] = $this->request->param('nr');
        $ins['zp']=$this->request->param('zp');
       $userid = $this->request->param('userid');
        if($userid)
            $eid=$this->geteid($userid);
        else
            $eid=session('employee_id');
        $ins["em_id"]=$eid;
        //$ins['zp'] = $this->request->param('zp');
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('zp');

        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            //最大50M
            $info = $file->validate(['size'=>50*1024*1024,'ext'=>'jpg,bnp,gif,png,jpeg,tif,raw,doc,docx,xls,xlsx,ppt,pptx,txt,pdf,rar,zip,mp4,avi,rmvb,rm,mid,3gp,AVI,3GP,,mpg,mp3,wma,wav'])->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                // 成功上传后 获取上传信息
                // 输出 jpg
                $info->getExtension();
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                $info->getSaveName();
                // 输出 42a79759f284b767dfcb2a0197904287.jpg
                $info->getFilename();

                $info2 = $info->getInfo();

                $data = [];
                $data['file_name'] =  $info2['name'];//原名
                $data['path'] =  $info->getSaveName();
                $bool = Db::table('annex')->insert($data);
                if(false !== $bool) {
                    $id = Db::table('annex')->getLastInsID();
                    $ins['zp'] = $id;
                }else{
                    echo json_encode(array( 'success' => false, 'msg' => '存储发生错误!请联系管理员!'));
                    die;
                }

            }else{
                // 上传失败获取错误信息
                echo json_encode(array('msg'=>$file->getError(),'success'=>false));die;
            }
        }
        $bool = db('yd_gzrb')->insert($ins);
        if(false!==$bool)
            echo json_encode(['success'=>1,'msg'=>'操作成功']);
        else
            echo json_encode(['success'=>0,'msg'=>'操作失败']);
    }

    /**
     * 日报点赞
     */
    public function rbdz(){
        $id = $this->request->param('id');
        $bool = db('yd_gzrb')->where('id',$id)->setInc('dzs');
        if(false!==$bool)
            echo json_encode(['success'=>1,'msg'=>'操作成功']);
        else
            echo json_encode(['success'=>0,'msg'=>'操作失败']);
    }

    /**
     * 日报评论
     */
    public function rbpl(){
        $data = [];
        $data['gzrb_id'] = $this->request->param('id');
        $data['content'] = $this->request->param('content');
        $userid = $this->request->param('userid');
        if($userid)
            $data['em_id'] = $this->geteid($userid);
        else
            $data['em_id'] = session('employee_id');
        $bool = db('yd_gzrb_pl')->insert($data);
        if(false!==$bool)
            echo json_encode(['success'=>1,'msg'=>'操作成功']);
        else
            echo json_encode(['success'=>0,'msg'=>'操作失败']);
    }

    /**
     * 经销商拜访
     */
    public function jxsbf(){
        $where = "1=1";
        $keyword = $this->request->param('keyword');
        if($keyword){
           
            $where = "title like '%{$keyword}%'";
        }

       // $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('cg_jxs')->order('id desc')->where($where)->field('id,title,sn,addr')->select();
        //echo db("cg_jxs")->getLastSql();exit;
        foreach($data as $k=>$v){
            $v['scbf'] = db('yd_jxsbf')->where('jxs',$v['id'])->order('bgrq desc')->value('bgrq');
           // $v['bfid'] = db('yd_jxsbf')->where('jxs',$v['id'])->order('bgrq desc')->value('id');
            $v['jhbf'] = db('yd_jxsbf')->where('jxs',$v['id'])->order('bgrq desc')->value('xcbfrq');
            $cishu=db("yd_jxsbf")->where('jxs',$v['id'])->count();
            if($cishu)
                $v["cishu"]=$cishu;
            else
                $v["cishu"]=0;
            $data[$k] = $v;
        }
        echo json_encode(['data'=>$data]);
    }

    /**
     * 经销商拜访记录
     */
    public function jxsbfjl(){
        $id = $this->request->param('id');
        $where = [];
        $where['jxs'] = $id;
        //$page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('yd_jxsbf')->order('bgrq desc')->where($where)->field('id,bgrq,bcpfmb,bcbfxj')->select();
        foreach($data as $k=>$v){
            $data[$k] = $v;
        }
        echo json_encode($data);
    }
    /**
     * 经销商拜访记录详情
     */
    public function jxsbfjlxq(){
        $id = $this->request->param('id');
        $where = [];
        $where['id'] = $id;
        $data = db('yd_jxsbf')->where($where)->field('qtsj,qtdz,bcbfxjzp,qtpz,bcbfxj,xcbfrq,xcbfmb,bfjhtp,jxs_title,bgrq as bfrq')->select();

        //print_r($data);exit;
        echo json_encode($data);
    }
    /**
     * 拜访签到
     */
    public function bfqd(){
        $data = [];

        $data['qdsj'] = date('Y-m-d H:i:s');
        $data['qddz'] = $this->request->param('qddz');
        $data['qdpz'] = $this->request->param('qdzp');
        $jid = $this->request->param('id');
        $uid = $this->request->param('userid');
        $eid=$this->geteid($uid);
        $has=db('yd_jxsbf')->where("jxs={$jid} and qtsj is null and qdsj is not null and bfr=$eid")->value("id");
        if($data['qddz']){
            if($has){
                echo json_encode(['success'=>0,'msg'=>'您存在未签退的拜访，请先执行拜访签退']);
            }else{
                //判断是否有存在任务
                $isneed=db('yd_jxsbf')->where("jxs={$jid} and qdsj is null and bfr=$eid")->value("id");
                $data["bfr"]=$eid;
                $data["bfr_name"]=db("employee")->where(["id"=>$eid])->value("em_name");
                $data["bfrbm"]=db("department_employee de")->join("department d","de.department_id=d.id")->where(["de.index"=>1,"de.employee_id"=>$eid])->value("d.de_name");
                $data["bfrgw"]=db("job_employee je")->join("job j","je.job_id=j.id")->where(["je.employee_id"=>$eid])->value("job_name");
                $data["jxs"]=$jid;
                $data["jxs_title"]=db("cg_jxs")->where(["id"=>$jid])->value("title");
                if($isneed){
                    //匹配任务签到
                    $data["id"]=$isneed;
                    $bool = db('yd_jxsbf')->update($data);
                }else{
                    //零时拜访
                    $data["bfzdr"]=$eid; $data['bgrq'] =date("Y-m-d");
                    $jxs=db("cg_jxs")->where(["id"=>$jid])->field("zoning,provice,city")->find();
                    $data["jxsssfq"]=db("cg_market_zoning")->where(["id"=>$jxs["zoning"]])->value("title");
                    $data["jxssssf"]=db("cg_market_provice")->where(["id"=>$jxs["provice"]])->value("title");
                    $data["jxssscs"]=db("cg_market_city")->where(["id"=>$jxs["city"]])->value("title");
                    $bool = db('yd_jxsbf')->insert($data);
                }
                
                
                if(false!==$bool)
                    echo json_encode(['success'=>1,'msg'=>'操作成功']);
                else
                    echo json_encode(['success'=>0,'msg'=>'操作失败']);
            }
        }else
            echo json_encode(['success'=>0,'msg'=>'签到地址不能为空']);
        
        
    }

    /**
     * 拜访小结
     */
    public function bfxj(){
        $where = [];
        $data = [];
        $jid=$this->request->param('id');
        $uid = $this->request->param('userid');
        $eid=$this->geteid($uid);
        $has=db('yd_jxsbf')->where("jxs={$jid} and  qdsj is not null and bfr=$eid")->order("qdsj desc")->value("id");
        if($has){
            $where['id'] =  $has;
            $data['bcbfxj'] = $this->request->param('bcbfxj');
            $data['bcbfxjzp'] = $this->request->param('bcbfxjzp');
            if(trim($data['bcbfxj'])){
                
                $hasxj=db('yd_jxsbf')->where($where)->value("bcbfxj");
                    if($hasxj){
                        echo json_encode(['success'=>0,'msg'=>'您已经完成了最近一次拜访的小结，不可重复提交']);
                    }else{
                        $bool = db('yd_jxsbf')->where($where)->update($data);
                        if(false!==$bool)
                            echo json_encode(['success'=>1,'msg'=>'操作成功']);
                        else
                            echo json_encode(['success'=>0,'msg'=>'操作失败']);
                    }
                    
                
            }else{
                echo json_encode(['success'=>0,'msg'=>'小结内容不能为空']);
            }
        }else{
            echo json_encode(['success'=>0,'msg'=>'您不存在已经签到的拜访，不能进行小结']);
        }
        

        
        
    }
    /**
     * 下次拜访计划
     */
    public function xcbfjh(){
        $where = [];
        $data = [];
        $jid=$this->request->param('id');
        $uid = $this->request->param('userid');
        $eid=$this->geteid($uid);
        $has=db('yd_jxsbf')->where("jxs={$jid} and  qdsj is not null and bfr=$eid")->order("qdsj desc")->value("id");
        if($has){
            $where['id'] =  $has;
            $data['xcbfrq'] = $this->request->param('xcbfrq');
            $data['xcbfmb'] = $this->request->param('xcbfmb');
            $data['bfjhtp'] = $this->request->param('sczp');
            if($data['xcbfrq']&&$data['xcbfmb']){
                $hasxc=db('yd_jxsbf')->where($where)->value("xcbfrq");
                    if($hasxc){
                        echo json_encode(['success'=>0,'msg'=>'您已经完成了最近一次本人拜访下次拜访计划设置，不可重复提交']);
                    }else{
                        $bool = db('yd_jxsbf')->where($where)->update($data);
                        if(false!==$bool)
                            echo json_encode(['success'=>1,'msg'=>'操作成功']);
                        else
                            echo json_encode(['success'=>0,'msg'=>'操作失败']);
                    }
                    
                
            }else{
                echo json_encode(['success'=>0,'msg'=>'下次拜访日期或目标不能为空']);
            }
        }else{
            echo json_encode(['success'=>0,'msg'=>'您不存在已经签到的拜访，不能进行小结']);
        }
        
        
    }
    /**
     * 拜访签退
     */
    public function pfqt(){
        $where = [];
        $jid=$this->request->param('id');
        $uid = $this->request->param('userid');
        $eid=$this->geteid($uid);
        $has=db('yd_jxsbf')->where("jxs={$jid} and  qdsj is not null and bfr=$eid")->order("qdsj desc")->value("id");
        if($has){
            $where['id'] =  $has;
            $data = [];
            $data['qtdz'] = $this->request->param('qtdz');
            $data['qtpz'] = $this->request->param('qtzp');
            $data['qtsj'] =date("Y-m-d H:i:s");
            if($data['qtdz']){
               
                $hasqt=db('yd_jxsbf')->where($where)->value("qtsj");
                    if($hasqt){
                        echo json_encode(['success'=>0,'msg'=>'您已经完成了本次拜访签退，不可重复提交']);
                    }else{
                        $qdsj=db('yd_jxsbf')->where($where)->value("qdsj");
                        
                        $ys=time()-strtotime($qdsj);
                        $ys=round($ys/60);
                            $data["ys"]=$ys;
                            $bool = db('yd_jxsbf')->where($where)->update($data);
                            if(false!==$bool)
                                echo json_encode(['success'=>1,'msg'=>'操作成功']);
                            else
                                echo json_encode(['success'=>0,'msg'=>'操作失败']);
                        
                       
                    }
                   
                
            }else{
                echo json_encode(['success'=>0,'msg'=>'签退地址不能为空']);
            }
        }else{
            echo json_encode(['success'=>0,'msg'=>'您不存未签退的拜访']);
        }

        
        
        
        
    }

    /**
     * 网点拜访列表
     */
    public function wdbflb(){
        $where = "";
        $type = $this->request->param('type');
        $date=date("Y-m-d");
        if($type==1){
            $where="rq='{$date}' ";
        }else{
            $where="rq<>'{$date}' and zt=0 ";
        }
            

        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('yd_wdbf')->order('id desc')->where($where)->limit(($page-1)*10,10)->select();
        foreach($data as $k=>$v){

            $data[$k] = $v;
            $data[$k]["netsn"]=db("cg_net")->where(["id"=>$v["wdid"]])->value("sn");
            
            $yifang=db('yd_wdbf')->where("wdid={$v["wdid"]} and (ddsj is not null or qddd is not null)")->count();
            if($yifang)
                $data[$k]["cishu"]=$yifang;
            else
                $data[$k]["cishu"]=0;
            if($v["qddd"])
                $data[$k]["yifang"]=1;
            else
                $data[$k]["yifang"]=0;
            $shangci=db('yd_wdbf')->where("wdid={$v["wdid"]} and (ddsj is not null or qddd is not null)")->order("ddsj desc")->value("ddsj");
            if($shangci){
                $data[$k]["shangci"]=$shangci;
            }else{
                $data[$k]["shangci"]="";
            }
            $data[$k]["isdg"]=db("cg_net")->where(["id"=>$v["wdid"]])->value("guide");
            $data[$k]["iszy"]=db("cg_net")->where(["id"=>$v["wdid"]])->value("direct");
            $data[$k]["iskey"]=db("cg_net")->where(["id"=>$v["wdid"]])->value("iskey");
            $data[$k]["wddz"]=db("cg_net")->where(["id"=>$v["wdid"]])->value("detailAddress");

        }
        $today=strtotime(date("Y-m-d"));
        $count=db("cg_ti t")->join("cg_ti_list td","td.ti_id=t.id")->where("t.status=7 and (t.status2 is null or t.status2=0) and td.start<={$today} and td.end>={$today} and td.net_id is not null")->group("td.net_id")->count();
        echo json_encode(['count'=>$count,'data'=>$data]);
    }

    /**
     * 网点拜访记录详情
     */
    public function wdbfjlxq(){
        $id = $this->request->param('id');
        $where = [];
        $where['id'] = $id;
        $data = db('yd_wdbf')->where($where)->field('wdmc,bfmb')->find();
        echo json_encode($data);
    }

    /**
     * 网点拜访签到
     */
    public function wdbfqd(){
        $data = [];
        //$data['rq'] = date('Y-m-d');
        $uid=$this->request->param('userid');
        $data['bfr'] = $this->geteid($uid);
        $data["ddsj"]=date("Y-m-d H:i:s");
        $data['id'] = $this->request->param('id');
        $data['qddd'] = $this->request->param('qddz');
        $data['qdtp'] = $this->request->param('qdzp');
        $has= db('yd_wdbf')->where(["id"=>$data["id"]])->value("ddsj");
        if($has){
            echo json_encode(['success'=>0,'msg'=>'已完成签到不能重复']);
        }else{
            if(trim($data["qddd"])){
                $bool = db('yd_wdbf')->update($data);
                if(false!==$bool)
                    echo json_encode(['success'=>1,'msg'=>'操作成功']);
                else
                    echo json_encode(['success'=>0,'msg'=>'操作失败']);
            }else{
                echo json_encode(['success'=>0,'msg'=>'签到地点不能为空']);
            }
            
        }
        
    }

    /**
     * 本公司导购
     */
    public function bgsdg(){
        $id = $this->request->param('id');
        /*$page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('cg_net_dg')->where('net_id',$id)->limit(($page-1)*10,10)->select();
        $cnt = db('cg_net_dg')->where('net_id',$id)->count();*/
        $where="mainNet_id=$id or otherNet_id=$id or otherNet_id like '%{$id},%' or otherNet_id like '%,{$id}%'";
        $dgs=db("bx_guide_user")->where($where)->field("id,name,workNumber,phone,postType,nowState")->select();
        //状态0 在职  1试用   2离职
        $cnt=db("bx_guide_user")->where($where)->count();
        if(!$cnt)
            $cnt=0;
        $dg=[];
        foreach ($dgs as $k => $v) {
            # code...
            $dg[$k]["id"]=$v["id"];
            $dg[$k]["xm"]=$v["name"];
            $dg[$k]["workNumber"]=$v["workNumber"];
            $dg[$k]["zgjl"]="";
            $dg[$k]["gwlx"]=$v["postType"];
            $dg[$k]["lxfs"]=$v["phone"];
            $dg[$k]["mqzt"]=$v["nowState"];
        }
        echo json_encode(['cnt'=>$cnt,'data'=>$dg]);
    }
    /**
     * 导购员在岗检查
     */
    public function dgyzgjc(){
       $id = $this->request->param('id');
       $data = db('cg_net_dg')->where('id',$id)->find();
       $data["net"]=db("cg_net")->where(["id"=>$data["net_id"]])->value("title");
       echo json_encode($data);
    }
    /**
     * 导购员在岗检查-提交
     */
    public function dgyzgjctj(){
        $data = [];
        $data['dz'] = $this->request->post('dz');
        $data['dg_id'] = $this->request->post('dg_id');
        $data['sfzg'] = $this->request->post('sfzg');
        $data['jcms'] = $this->request->post('jcms');
        $data['sczp'] = $this->request->post('sczp');
        $bool = db('yd_dgyzgjc')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }

    /**
     * 经销商导购
     */
    public function jxsdg(){
        $id = $this->request->param('id');
        $jxs_id = db('cg_jxs t')
            ->join('cg_system t2','t2.jxs=t.id')
            ->join('cg_net t3','t3.system_id=t2.id')
            ->where('t3.id',$id)
            ->value('t.id');

        $net_ids = db('cg_jxs t')
            ->join('cg_system t2','t2.jxs=t.id')
            ->join('cg_net t3','t3.system_id=t2.id')
            ->where('t.id',$jxs_id)
            ->column('t3.id');
        $jxs=db("cg_jxs")->where(["id"=>$jxs_id])->value("title");
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('cg_net_dg')->where('net_id','in',$net_ids)->limit(($page-1)*10,10)->select();
        foreach ($dg as $k => $v) {
            # code...
            $dg[$k]["net"]=db("cg_net")->where(["id"=>$v["net_id"]])->value("title");
        }
        $cnt = db('cg_net_dg')->where('net_id','in',$net_ids)->count();
        echo json_encode(['jxs'=>$jxs,'cnt'=>$cnt,'data'=>$dg]);
    }

    /**
     * 物料检查
     */
    public function wljc(){
        $id = $this->request->param('id');
        $bf_id=$this->request->param('bf_id');
        
        $dg = db('yd_wljc')->where('bf_id',$bf_id)->field("id,wlmc,jcjg,jcskcsl,jcms")->select();
        //print_r($dg);exit;
        echo json_encode($dg);
    }

    /**
     * 添加物料检查
     */
    public function tjwljc(){
        $data = [];
        $data['wlmc'] = $this->request->param('wlmc');
        $data['jcjg'] = $this->request->param('jcjg');
        $data['jcskcsl'] = $this->request->param('sl');
        $data['jcms'] = $this->request->param('jcms');
        $data['zp'] = $this->request->param('zp');
        $data['bf_id'] = $this->request->param('bf_id');
        $bf=db("yd_wdbf")->where(["id"=>$data["bf_id"]])->find();
        if(!$bf){
            echo json_encode(['success'=>false,'msg'=>'拜访不存在']);die;
        }
        $data["net_id"]=$bf["wdid"];
        if($data["net_id"]&&$data['bf_id']){
            if($data["wlmc"]){
                $net=db("cg_net")->where(["id"=>$data['net_id']])->find();
                $data['hbwdbm']=$net["sn"];
                $data['hbwd']=$net["title"];
                $uid=$this->request->param('userid');
                $eid=$this->geteid($uid);
                $data['hbr_id'] = $eid;
                $em=db("employee")->where("id=$eid")->find();
                $data["hbr_xm"]=$em["em_name"];
                $data['hbr_bm'] = db('department t')->join('department_employee t2','t.id=t2.department_id')->where('t2.employee_id',$eid)->value('t.de_name');
                $data['hbr_gw'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$eid)->value('t.job_name');
                $data['hbr_sjh'] =$em["mobile"];
                $data['hbrq']=date("Y-m-d");
                $bool = db('yd_wljc')->insert($data);
                if(false!==$bool){
                    echo json_encode(['success'=>true,'msg'=>'or']);
                }else{
                    echo json_encode(['success'=>false,'msg'=>'error']);
                }
            }else{
                echo json_encode(['success'=>false,'msg'=>'物料名称不能空']);
            }
            
        }else{
            echo json_encode(['success'=>false,'msg'=>'网点id和拜访id不能为空']);
        }
       
    }
    //仓库列表
    public function cklist(){
        $data=db("cg_ck")->field("id,ckjc as title")->select();
        echo json_encode($data);die;
    }
    //物料类型
    public function mattype(){
        $data[]=["id"=>1,"title"=>"生产物料"];
        $data[]=["id"=>2,"title"=>"销售物料"];
        $data[]=["id"=>3,"title"=>"成品"];
        echo json_encode($data);die;
    }
    //库存查询
    public function kccx(){
        $data['ck'] = $this->request->param('ck');
        $data['wlxl'] = $this->request->param('wlxl');
        $data['wlbh'] = $this->request->param('wlbh');
        $data['wlmc'] = $this->request->param('wlmc');
        $where="1=1 ";
        if($data["ck"])
            $where.="and ck={$data["ck"]} ";
        if($data["wlxl"])
            $where.="and wlxl={$data["wlxl"]} ";
        if($data["wlbh"])
            $where.="and wlbh like '%{$data["wlxl"]}%' ";
        if($data["wlmc"])
            $where.="and wlmc like '%{$data["wlxl"]}%' ";
        $data=db("yd_kccx")->where($where)->group("wlbh")->field("wlbh,wlmc,wllb,sum(kcsl) as kc,kcdw")->select();
        echo json_encode($data);die;
    }
    public function xxtixing(){
        $userid = $this->request->param('userid');
        $eid=$this->geteid($userid);
        $data=db("yd_xxset")->where(["eid"=>$eid])->field("set1,set2")->find();
        if(!$data)
            $data=["set1"=>0,"set2"=>0];
        echo json_encode($data);die;
    }
    public function xxset(){
        $userid = $this->request->param('userid');
        $set1 = $this->request->param('set1');
        $set2 = $this->request->param('set2');
        $eid=$this->geteid($userid);
        $data=db("yd_xxset")->where(["eid"=>$eid])->field("set1,set2")->find();
        if($data){
            db("yd_xxset")->where(["eid"=>$eid])->update(["set1"=>$set1,"set2"=>$set2]);
            $bool = 1;
        }else{
            $bool = db("yd_xxset")->insert(["eid"=>$eid,"set1"=>$set1,"set2"=>$set2]);
        }
         if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'or']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
    }
    /*
        修改原始数据

     */
    public function wljcmx(){
        $id = $this->request->param('id');
        $data=db('yd_wljc')->where('id',$id)->field("wlmc,jcjg,jcskcsl as sl,jcms,zp")->find();
        echo json_encode($data);
    }
    /**
     * 修改物料检查
     */
    public function xgwljc(){
            $id = $this->request->param('id');
            //echo $id;exit;
            if($id){
                 $data = [];
                $data['wlmc'] = $this->request->param('wlmc');
                $data['jcjg'] = $this->request->param('jcjg');
                if($data["wlmc"]&&$data["jcjg"]){
                     $data['jcskcsl'] = $this->request->param('sl');
                    $data['jcms'] = $this->request->param('jcms');
                    $data['zp'] = $this->request->param('zp');
                  
                    $uid=$this->request->param('userid');
                    if($uid){
                        $eid=$this->geteid($uid);
                        $data['hbr_id'] = $eid;
                        $em=db("employee")->where("id=$eid")->find();
                        $data["hbr_xm"]=$em["em_name"];
                        $data['hbr_bm'] = db('department t')->join('department_employee t2','t.id=t2.department_id')->where('t2.employee_id',$eid)->value('t.de_name');
                        $data['hbr_gw'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$eid)->value('t.job_name');
                        $data['hbr_sjh'] =$em["mobile"];
                        $data['hbrq']=date("Y-m-d");
                        $bool = db('yd_wljc')->where(['id'=>$id])->update($data);
                        if(false!==$bool){
                            echo json_encode(['success'=>true,'msg'=>'or']);
                        }else{
                            echo json_encode(['success'=>false,'msg'=>'error']);
                        }
                    }else{
                        echo json_encode(['success'=>false,'msg'=>'error']);
                    }
                        
                }else{
                    echo json_encode(['success'=>false,'msg'=>'物料名称和检查结果不能为空']);
                }
               
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
           

        
    }

    /**
     * 删除物料检查
     */
    public function scwljc(){
        $id = $this->request->param('id');
        $bool = db('yd_wljc')->where('id',$id)->delete();
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'or']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
        die;
    }

    /**
     * 货架陈列
     */
    public function hjcl(){
        $id = $this->request->param('id');
        $bf_id=$this->request->param('bf_id');
       
        $dgs = db('yd_hjcl')->where('bf_id',$bf_id)->order("rq desc")->select();
        $dg=[];
        foreach ($dgs as $k => $v) {
            # code...
            $dg[$k]["clid"]=$v["id"];
            $dg[$k]["cp_id"]=$v["cp_id"];
            $dg[$k]["cpmc"]=$v["cpmc"];
            $dg[$k]["cllx"]=db("yd_hjcllx")->where(["id"=>$v["cllx"]])->value("title");
            if($v["zt"]==1)
                $dg[$k]["zt"]="正常";
            else
                $dg[$k]["zt"]="异常";
            $dg[$k]["clwz_p"]=$v["clwz_p"];$dg[$k]["clwz_m"]=$v["clwz_m"];
            $dg[$k]["cxhd"]=$v["cxhd"];$dg[$k]["sm"]=$v["sm"];$dg[$k]["rq"]=$v["rq"];
        }
        echo json_encode($dg);
    }

    /**
     * 添加货架陈列
     */
    public function tjhjcl(){
        $data = [];
        $data['cllx'] = $this->request->param('cllx');
        $data['zt'] = $this->request->param('zt');
        $data['clwz_p'] = $this->request->param('clwz_p');
        $data['clwz_m'] = $this->request->param('clwz_m');
        $data['cxhd'] = $this->request->param('cxhd');
        $data['sm'] = $this->request->param('sm');
        $data['eid'] =$this->geteid($this->request->param('userid'));
        $data['sczp'] = $this->request->param('sczp');
        //$data['net_id'] = $this->request->param('id');
        $data['cp_id'] = $this->request->param('cp_id');
        $data['rq']=date("Y-m-d");
        $data["bf_id"]= $this->request->param('bf_id');
        $bf=db("yd_wdbf")->where(["id"=>$data["bf_id"]])->find();
        if(!$bf){
            echo json_encode(['success'=>false,'msg'=>'拜访不存在']);die;
        }
        $data["net_id"]=$bf["wdid"];
        if($data['net_id']&&$data["bf_id"]){
            if($data['zt']&&$data['cp_id']||$data['cllx']){
                $data["cpmc"]=db("pro_products")->where(["id"=>$data["cp_id"]])->value("pro_name");
                $bool = db('yd_hjcl')->insert($data);
                if(false!==$bool){
                    echo json_encode(['success'=>true,'msg'=>'or']);
                }else{
                    echo json_encode(['success'=>false,'msg'=>'error']);
                }
            }else{
                echo json_encode(['success'=>false,'msg'=>'陈列类型，产品和状态为必填项']);
            }
            
        }else{
            echo json_encode(['success'=>false,'msg'=>'网点或拜访id没有传入']);
        }
        
    }
    /**
     * 货架陈列类型
     */
     public function hjcllx(){
       
        $dg = db('yd_hjcllx')->select();
        echo json_encode($dg);
    }
    /**
     * 临期类型
     */
     public function kctype(){
       
        $dg = db('yd_kcjx_lx')->select();
        echo json_encode($dg);
    }
    public function hjclde(){
        $id = $this->request->param('id');
        $data = db('yd_hjcl')->where('id',$id)->find();
        echo json_encode($data);
    }
    /**
     * 修改货架陈列
     */
    public function xghjcl(){
        $id = $this->request->param('id');
        
        $data['cllx'] = $this->request->param('cllx');
        $data['zt'] = $this->request->param('zt');
        $data['clwz_p'] = $this->request->param('clwz_p');
        $data['clwz_m'] = $this->request->param('clwz_m');
        $data['cxhd'] = $this->request->param('cxhd');
        $data['sm'] = $this->request->param('sm');
        $data['eid'] =$this->geteid($this->request->param('userid'));
        $data['sczp'] = $this->request->param('sczp');
       
        $data['cp_id'] = $this->request->param('cp_id');
        $data['rq']=date("Y-m-d");
        if($data['zt']&&$data['cp_id']||$data['cllx']){
            $data["cpmc"]=db("pro_products")->where(["id"=>$data["cp_id"]])->value("pro_name");
            $bool = db('yd_hjcl')->where('id',$id)->update($data);
            if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'or']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
        }else{
            echo json_encode(['success'=>false,'msg'=>'陈列类型，产品和状态为必填项']);
        }
       
    }

    /**
     * 删除货架陈列
     */
    public function schjcl(){
        $id = $this->request->param('id');
        $bool = db('yd_hjcl')->where('id',$id)->delete();
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'or']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
        die;
    }

    /**
     * 产品检查
     */
    public function cpjc(){
        $id = $this->request->param('id');
        $bf_id=$this->request->param('bf_id');
        $jinchang=db("cg_net_barcode")->where(["net_id"=>$id,"tuichang"=>0])->select();
        $dg=[];
        foreach ($jinchang as $k => $v) {
            # code...
            $dg[$k]["cp_id"]=$v["prod"];
            $dg[$k]["pro_name"]=db("pro_products")->where(["id"=>$v["prod"]])->value("pro_name");
            $dg[$k]["unit"]=db("pro_products")->where(["id"=>$v["prod"]])->value("unit");
            $hasck=db("yd_cpjc")->where(["bf_id"=>$bf_id,"cp_id"=>$v["prod"]])->find();
            if($hasck){
                //存在检查
                $dg[$k]["jcqk_zt"]=$hasck["jcqk_zt"];
                $dg[$k]["jcqk_jg"]=$hasck["jcqk_jg"];
                $dg[$k]["jcqk_bz"]=$hasck["jcqk_bz"];
            }else{
                //不存在检查
                $dg[$k]["jcqk_zt"]='';
                $dg[$k]["jcqk_jg"]='';
                $dg[$k]["jcqk_bz"]='';
            }
        }
        //$dg = db('yd_cpjc')->where('net_id',$id)->limit(($page-1)*10,10)->select();
        echo json_encode(['data'=>$dg]);
    }
    /*产品检查明细*/
    public function cpjcmx(){
        $bf_id=$this->request->param('bf_id');
        $pid=$this->request->param('cp_id');
        $dg["pro_name"]=db("pro_products")->where(["id"=>$pid])->value("pro_name");
        $dg["unit"]=db("pro_products")->where(["id"=>$pid])->value("unit");
        $dg["cp_id"]=$pid;
        $hasck=db("yd_cpjc")->where(["bf_id"=>$bf_id,"cp_id"=>$pid])->find();
        if($hasck){
            $dg["jcqk_zt"]=$hasck["jcqk_zt"];
            $dg["jcqk_jg"]=$hasck["jcqk_jg"];
            $dg["jcqk_bz"]=$hasck["jcqk_bz"];
        }else{
            $dg["jcqk_zt"]='';
            $dg["jcqk_jg"]='';
            $dg["jcqk_bz"]='';
        }
        echo json_encode(['data'=>$dg]);
    }
    /*产品检查修改*/
    public function xgcpjc(){
        $bf_id=$this->request->param('bf_id');
        $pid=$this->request->param('cp_id');
        if(!$bf_id){
            echo json_encode(['success'=>false,'msg'=>'拜访id不存在']);die;
        }
        if(!$pid){
            echo json_encode(['success'=>false,'msg'=>'产品id不存在']);die;
        }
        $data["jcqk_zt"]=$this->request->param('jcqk_zt');
        $data["jcqk_jg"]=$this->request->param('jcqk_jg');
        $data["jcqk_bz"]=$this->request->param('jcqk_bz');
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $data["hbr_id"]=$eid;
        $data["hbrq"]=date("Y-m-d H:i:s");
        $hasck=db("yd_cpjc")->where(["bf_id"=>$bf_id,"cp_id"=>$pid])->find();

        if($hasck){
            //存在修改
            $bool=db("yd_cpjc")->where(["bf_id"=>$bf_id,"cp_id"=>$pid])->update($data);
        }else{
            //不存在新增
            $data["bf_id"]=$bf_id;
            $bf=db("yd_wdbf")->where(["id"=>$data["bf_id"]])->find();
            if(!$bf){
                echo json_encode(['success'=>false,'msg'=>'拜访不存在']);die;
            }
            $data["net_id"]=$bf["wdid"];
            $data["cp_id"]=$pid;
            $bool=db("yd_cpjc")->insert($data);
        }
        if(false!==$bool){
                        echo json_encode(['success'=>true,'msg'=>'or']);
                    }else{
                        echo json_encode(['success'=>false,'msg'=>'error']);
                    }
    }
    //添加进场条码产品下拉框
    public function nocodelist(){
        $net_id=$this->request->param('net_id');
        $hasj=[];
        $jinchang=db("cg_net_barcode")->where(["net_id"=>$net_id,"tuichang"=>0])->select();
        foreach ($jinchang as $k => $v) {
            # code...
            $hasj[]=$v["prod"];
        }
        if($hasj){
            $nos=implode(',',$hasj);
            $pro=db("pro_products")->where("is_deleted=0 and is_actived=1 and id not in ($nos)")->field("id,pro_name")->select();
        }else{
            $pro=db("pro_products")->where("is_deleted=0 and is_actived=1")->field("id,pro_name")->select();
        }
        echo json_encode(['data'=>$pro]);
    }
    //添加进场条码处理
    public function addbarcode(){
        $data["net_id"]=$this->request->param('net_id');
        $data["prod"]=$this->request->param('pro_id');
        $data["intime"]=strtotime($this->request->param('intime'));
        $data["infee"]=$this->request->param('infee');
        $data["retailPrice"]=$this->request->param('price');
        $data["zp"]=$this->request->param('zp');
        if(!$data["net_id"]){
            echo json_encode(['success'=>false,'msg'=>'请正确传入网点id']); die;
        }
        if(!$data["prod"]){
            echo json_encode(['success'=>false,'msg'=>'请正确传入产品id']);die;
        }
        if($data["intime"]&&$data["infee"]&&$data["retailPrice"]){
            $bool = db('cg_net_barcode')->insert($data);
                    if(false!==$bool){
                        echo json_encode(['success'=>true,'msg'=>'or']);die;
                    }else{
                        echo json_encode(['success'=>false,'msg'=>'error']);die;
                    }
        }else{
            echo json_encode(['success'=>false,'msg'=>'进场时间，进场费，零售价不能为空']);die;
        }
    }
    /**
     * 库存检查
     */
    public function kcjc(){
        $id = $this->request->param('id');
        $bf_id=$this->request->param('bf_id');
       
        $dgs = db('yd_kcjc')->where('bf_id',$bf_id)->select();
        $dg=[];
        foreach ($dgs as $k => $v) {
            # code...
            $dg[$k]["id"]=$v["id"];
            $dg[$k]["cp_id"]=$v["cp_id"];
            $dg[$k]["cp_dpmc"]=$v["cp_dpmc"];
            $dg[$k]["kcqk_lx"]=$v["kcqk_lx"];
            $dg[$k]["kcqk_lx_title"]=db("yd_kcjx_lx")->where(["id"=>$v["kcqk_lx"]])->value("title");
            $dg[$k]["kcqk_kcsl_x"]=$v["kcqk_kcsl_x"];$dg[$k]["kcqk_kcsl_z"]=$v["kcqk_kcsl_z"];
            $dg[$k]["kcqk_scrq"]=$v["kcqk_scrq"];
            $dg[$k]["kcqk_scrq"]=$v["kcqk_scrq"];
            $dg[$k]["sm"]=$v["bz"];
            $dg[$k]["zp"]=$v["zp"];

        }
        echo json_encode(['data'=>$dg]);
    }

    /**
     * 添加库存检查
     */
    public function tjkcjc(){
        $data = [];
       // $data['cp_dpmc'] = $this->request->param('cp_dpmc');
        $data['kcqk_lx'] = $this->request->param('kcqk_lx');
        $data['kcqk_scrq'] = $this->request->param('kcqk_scrq');
        $data['kcqk_kcsl_x'] = $this->request->param('kcqk_kcsl_x');
        $data['kcqk_kcsl_z'] = $this->request->param('kcqk_kcsl_z');
        $data['bz'] = $this->request->param('sm');
        $data['zp'] = $this->request->param('zp');
        $uid=$this->request->param('userid');
        $data['cp_id'] = $this->request->param('cp_id');
         $data["bf_id"]= $this->request->param('bf_id');
        $bf=db("yd_wdbf")->where(["id"=>$data["bf_id"]])->find();
        if(!$bf){
            echo json_encode(['success'=>false,'msg'=>'拜访不存在']);die;
        }
        $data["net_id"]=$bf["wdid"];
        if($data["net_id"]&&$data["bf_id"]){
            $net=db("cg_net")->where(["id"=>$data['net_id']])->find();
            $data['hbwdbm']=$net["sn"];
            $data['hbwd']=$net["title"];
            if($uid){
                if($data["cp_id"]){
                    $data["cp_dpmc"]=db("pro_products")->where(["id"=>$data["cp_id"]])->value("pro_name");
                    $eid=$this->geteid($uid);
                    $data['hbr_id'] = $eid;
                    $em=db("employee")->where("id=$eid")->find();
                    $data["hbr_xm"]=$em["em_name"];
                    $data['hbr_bm'] = db('department t')->join('department_employee t2','t.id=t2.department_id')->where('t2.employee_id',$eid)->value('t.de_name');
                    $data['hbr_gw'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$eid)->value('t.job_name');
                    $data['hbr_sjh'] =$em["mobile"];
                    $data["hbrq"]=date("Y-m-d");
                    $bool = db('yd_kcjc')->insert($data);
                    if(false!==$bool){
                        echo json_encode(['success'=>true,'msg'=>'or']);
                    }else{
                        echo json_encode(['success'=>false,'msg'=>'error']);
                    }
                }else{
                    echo json_encode(['success'=>false,'msg'=>'请选择产品']);
                }
               
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
        }else{
            echo json_encode(['success'=>false,'msg'=>'请正确传入网点和拜访id']);
        }
        
    }
    public function kcjcmx(){
        $id = $this->request->param('id');
        $data = db('yd_kcjc')->where('id',$id)->field("cp_id,cp_dpmc,kcqk_lx,kcqk_scrq,kcqk_kcsl_x,kcqk_kcsl_z,bz as sm,zp")->find();
        $data["kcqk_lx_title"]=db("yd_kcjx_lx")->where(["id"=>$data["kcqk_lx"]])->value("title");
        echo json_encode($data);
    }
    /**
     * 修改库存检查
     */
    public function xgkcjc(){
        $data = [];
        $id = $this->request->param('id');
        $data['kcqk_lx'] = $this->request->param('kcqk_lx');
        $data['kcqk_scrq'] = $this->request->param('kcqk_scrq');
        $data['kcqk_kcsl_x'] = $this->request->param('kcqk_kcsl_x');
        $data['kcqk_kcsl_z'] = $this->request->param('kcqk_kcsl_z');
        $data['bz'] = $this->request->param('sm');
        $data['zp'] = $this->request->param('zp');
        $uid=$this->request->param('userid');
        $data['cp_id'] = $this->request->param('cp_id');
        if($uid){
                if($data["cp_id"]){
                    $data["cp_dpmc"]=db("pro_products")->where(["id"=>$data["cp_id"]])->value("pro_name");
                    $eid=$this->geteid($uid);
                    $data['hbr_id'] = $eid;
                    $em=db("employee")->where("id=$eid")->find();
                    $data["hbr_xm"]=$em["em_name"];
                    $data['hbr_bm'] = db('department t')->join('department_employee t2','t.id=t2.department_id')->where('t2.employee_id',$eid)->value('t.de_name');
                    $data['hbr_gw'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$eid)->value('t.job_name');
                    $data['hbr_sjh'] =$em["mobile"];
                    $data["hbrq"]=date("Y-m-d");
                    $bool = db('yd_kcjc')->where(["id"=>$id])->update($data);
                    if(false!==$bool){
                        echo json_encode(['success'=>true,'msg'=>'or']);
                    }else{
                        echo json_encode(['success'=>false,'msg'=>'error']);
                    }
                }else{
                    echo json_encode(['success'=>false,'msg'=>'请选择产品']);
                }
               
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
    }

    /**
     * 删除库存检查
     */
    public function sckcjc(){
        $id = $this->request->param('id');
        $bool = db('yd_kcjc')->where('id',$id)->delete();
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'or']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
        die;
    }
    /*销量汇报*/
    public function xlhb(){
        $id = $this->request->param('id');
        $bf_id=$this->request->param('bf_id');
        $jinchang=db("cg_net_barcode")->where(["net_id"=>$id,"tuichang"=>0])->select();
        $dg=[];
        foreach ($jinchang as $k => $v) {
            # code...
            $dg[$k]["cp_id"]=$v["prod"];
            $dg[$k]["pro_name"]=db("pro_products")->where(["id"=>$v["prod"]])->value("pro_name");
            $dg[$k]["unit"]=db("pro_products")->where(["id"=>$v["prod"]])->value("unit");
            $hasck=db("yd_wdxlhb")->where(["bf_id"=>$bf_id,"cp_id"=>$v["prod"]])->find();
            if($hasck){
                //存在检查
                $dg[$k]["xiang"]=$hasck["xiang"];
                $dg[$k]["zhi"]=$hasck["zhi"];
                $dg[$k]["bz"]=$hasck["bz"];
            }else{
                //不存在检查
                $dg[$k]["xiang"]='';
                $dg[$k]["zhi"]='';
                $dg[$k]["bz"]='';
            }
        }
        //$dg = db('yd_cpjc')->where('net_id',$id)->limit(($page-1)*10,10)->select();
        echo json_encode(['data'=>$dg]);    
    }
    /*销量汇报明细*/
    public function xlhbmx(){
        $bf_id=$this->request->param('bf_id');
        $pid=$this->request->param('cp_id');
        $dg["pro_name"]=db("pro_products")->where(["id"=>$pid])->value("pro_name");
        $dg["unit"]=db("pro_products")->where(["id"=>$pid])->value("unit");
        $dg["cp_id"]=$pid;
        $hasck=db("yd_wdxlhb")->where(["bf_id"=>$bf_id,"cp_id"=>$pid])->find();
        if($hasck){
            $dg["xiang"]=$hasck["xiang"];
            $dg["zhi"]=$hasck["zhi"];
            $dg["bz"]=$hasck["bz"];
        }else{
            $dg["xiang"]='';
            $dg["zhi"]='';
            $dg["bz"]='';
        }
        echo json_encode(['data'=>$dg]);
    }
    /**
     * 提交销量汇报
     */
    public function tjxlhb(){
        $bf_id=$this->request->param('bf_id');
        $pid=$this->request->param('cp_id');
        if(!$bf_id){
            echo json_encode(['success'=>false,'msg'=>'拜访id不存在']);die;
        }
        if(!$pid){
            echo json_encode(['success'=>false,'msg'=>'产品id不存在']);die;
        }
        $data["xiang"]=$this->request->param('a');
        $data["zhi"]=$this->request->param('g');
        $data["bz"]=$this->request->param('bz');
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $data["hbr_id"]=$eid;
        $data["hbrq"]=date("Y-m-d H:i:s");
        $hasck=db("yd_wdxlhb")->where(["bf_id"=>$bf_id,"cp_id"=>$pid])->find();

        if($hasck){
            //存在修改
            $bool=db("yd_wdxlhb")->where(["bf_id"=>$bf_id,"cp_id"=>$pid])->update($data);
        }else{
            //不存在新增
            $data["bf_id"]=$bf_id;
            $bf=db("yd_wdbf")->where(["id"=>$data["bf_id"]])->find();
            if(!$bf){
                echo json_encode(['success'=>false,'msg'=>'拜访不存在']);die;
            }
            $data["net_id"]=$bf["wdid"];
            $data["cp_id"]=$pid;
            $bool=db("yd_wdxlhb")->insert($data);
        }
        if(false!==$bool){
                        echo json_encode(['success'=>true,'msg'=>'or']);
                    }else{
                        echo json_encode(['success'=>false,'msg'=>'error']);
                    }
    }

    /**
     * 订单汇报
     */
    public function ddhb(){
        $bf_id = $this->request->param('bf_id');

        $nid=db("yd_wdbf")->where(["id"=>$bf_id])->value("wdid");
        $sid=db("cg_net")->where(["id"=>$nid])->value("system_id");
        $jid=db("cg_system")->where(["id"=>$sid])->value("jxs");
        $jxs=db("cg_jxs")->where(["id"=>$jid])->field("id,title")->find();
        $dg = db('cg_order')->where(['bf_id'=>$bf_id])->field("id,sn,cusName as net_id,khmc as net,shdz,shr,dh,yszje,zysx as bz,yhPolicy,yhPolicymc,status,sqrq")->select();
        foreach ($dg as $k => $v) {
            $dg[$k]["sqrq"]=date("Y-m-d H:i:s",$v["sqrq"]);
            # code...
            $dg[$k]["jid"]=$jxs["id"];
            $dg[$k]["jxs"]=$jxs["title"];
            if($dg[$k]["status"]==1){
                $dg[$k]["status"]="未处理";
            }else if($dg[$k]["status"]>=2 &&$dg[$k]["status"]<=6){
                $dg[$k]["status"]="流程中";
            }else if($dg[$k]["status"]==7){
                $dg[$k]["status"]="已通过";
            }else{
                $dg[$k]["status"]="未通过";
            }
        }
        echo json_encode(['data'=>$dg]);
    }
    public function ordermx(){
        $oid = $this->request->param('oid');
        $dg = db('cg_order')->where(['id'=>$oid])->field("id,sn,cusName as net_id,khmc as net,shdz,shr,dh,yszje,zysx as bz,yhPolicy,yhPolicymc,status,sqrq")->find();
        //print_r($dg);exit;
        $net=db("cg_net")->where(["id"=>$dg["net_id"]])->find();
        $dg["net_sn"]=$net["sn"];
        $jid=db("cg_system")->where(["id"=>$net["system_id"]])->value("jxs");
        $jxs=db("cg_jxs")->where(["id"=>$jid])->find();
        $dg["jxs"]=$jxs["title"];
        $dg["jsn"]=$jxs["sn"];
        $dg["sqrq"]=date("Y-m-d H:i:s",$dg["sqrq"]);
        if($dg["status"]==1){
            $dg["status"]="未处理";
        }else if($dg["status"]>=2&&$dg["status"]<=6){
            $dg["status"]="流程中";
        }else if($dg["status"]==7){
            $dg["status"]="已通过";
        }else{
            $dg["status"]="未通过";
        }
        $od=db("cg_order_list")->where("order_id=$oid")->select();
        $ods=[];
        foreach ($od as $k => $v) {
            # code...
            $ods[$k]["did"]=$v["id"];
            $ods[$k]["bz"]=$v["beizhu"];
            $ods[$k]["pro_name"]=$v["prod_name"];
            $ods[$k]["ghj"]=$v["xgj"];
            $num=$v["num"];
            $box_num=db("pro_products")->where(["id"=>$v["product"]])->value("box_num");
            $ods[$k]["box"]=floor($num/$box_num);
            $ods[$k]["ge"]=$num-$ods[$k]["box"]*$box_num;
            $ods[$k]["unit"]=db("pro_products")->where(["id"=>$v["product"]])->value("unit");
            $ods[$k]["status"]=$dg["status"];
            $ods[$k]["xslx"]=$v["xslx"];
            $str="";
            if($v["qdyhje"]){
                $str.="活动优惠金额:{$v["qdyhje"]};";
            }
            if($v["dzsl"]){
                $str.="搭赠数量:{$v["dzsl"]};";
            }
            if($v["hbsl"]){
                $str.="货补数量:{$v["hbsl"]};";
            }
            if($v["bfje"]){
                $str.="补费金额:{$v["bfje"]};";
            }
            $ods[$k]["yhms"]=$str;
        }
        $dg["detail"]=$ods;
        echo json_encode($dg);
    }
    /*新增订单默认基本数据*/
    public function orderdefault(){
        $bf_id = $this->request->param('bf_id');
        $nid=db("yd_wdbf")->where(["id"=>$bf_id])->value("wdid");
        $sid=db("cg_net")->where(["id"=>$nid])->value("system_id");
        $jid=db("cg_system")->where(["id"=>$sid])->value("jxs");
        $jxs=db("cg_jxs")->where(["id"=>$jid])->field("id,title,lgs_rcv_one,lgs_rcv_addr,lgs_rcv_phone")->find();
        $net=db("cg_net")->where(["id"=>$nid])->field("lgs_rcv_addr,lgs_rcv_one,lgs_rcv_phone")->find();
        $data=[];
        $data["jxs"]=$jxs["title"];
        $data["jxs_shr"]=$jxs["lgs_rcv_one"];
        $data["jxs_shdz"]=$jxs["lgs_rcv_addr"];
        $data["jxs_shdh"]=$jxs["lgs_rcv_phone"];
        $data["net_shr"]=$net["lgs_rcv_one"];
        $data["net_shdz"]=$net["lgs_rcv_addr"];
        $data["net_shdh"]=$net["lgs_rcv_phone"];
        echo json_encode($data);
    }
    /*促销活动列表*/
    public function youhuilist(){
        $nid= $this->request->param('net_id');
        $sid=db("cg_net")->where(["id"=>$nid])->value("system_id");
        $jxs_id=db("cg_system")->where(["id"=>$sid])->value("jxs");
        
        $city = db('cg_jxs')->where('id',$jxs_id)->value('city');
        $provice = db('cg_jxs')->where('id',$jxs_id)->value('provice');
        $zoning = db('cg_jxs')->where('id',$jxs_id)->value('zoning');
        //查询是否有渠道优惠政策
        $time = date('Y-m-d');
        $where="t.status=7 and t.is_revoke is null and ((area=1 and area_id like '%\"{$zoning}\"%') or (area=2 and area_id like '%\"{$provice}\"%') or (area=3 and area_id like '%\"{$city}\"%') or (area=4 and area_id like '%\"{$jxs_id}\"%') ) and td.start<='{$time}' and td.end>='{$time}'";
        $qdyhzc = db('cg_channel_preferential_policy t')->join("cg_channel_preferential_policy_cxfa td","td.p_id=t.id")
            ->where($where)->field('t.id,t.title,t.sn')->group("t.id")
            ->select();
        $data=[];
        foreach ($qdyhzc as $k => $v) {
            # code...
            $mingxi=db("cg_channel_preferential_policy_cxfa")->where("((area=1 and area_id like '%\"{$zoning}\"%') or (area=2 and area_id like '%\"{$provice}\"%') or (area=3 and area_id like '%\"{$city}\"%') or (area=4 and area_id like '%\"{$jxs_id}\"%') ) and start<='{$time}' and end>='{$time}' and p_id={$v["id"]}")->select();

            foreach ($mingxi as $km => $vm) {
                # code...
                $deid=db("cg_channel_preferential_policy_cxfa")->where("p_id={$v["id"]} and id<={$vm["id"]}")->count();
                $tmp["id"]=$vm["id"];
                $tmp["title"]=$v["title"].'-促销方案'.$deid;
                $data[]=$tmp;

            }
        }
        echo json_encode($data);
    }
     /**
     * 修改订单
     */
    public function xgdd(){
        $data = [];
        $id = $this->request->param('oid');
        $od=db("cg_order")->where("id=$id")->find();
        if(!$od){
            echo json_encode(['success'=>false,'msg'=>'订单不存在']);die;
        }
        if($od["status"]!=1){
            echo json_encode(['success'=>false,'msg'=>'订单状态不允许修改']);die;
        }
         $data['shr'] = $this->request->param('lxr');
        
        $data['dh'] = $this->request->param('dh');
        $data['shdz'] = $this->request->param('dz');
        $data['zysx'] = $this->request->param('bz');
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $data["ptime"]=time();
        $data["puser"]=$eid;
        $data["yhPolicy"]= $this->request->param('cuxiao_id');
        $yhtitle=db('cg_channel_preferential_policy p')->join("cg_channel_preferential_policy_cxfa pd","pd.p_id=p.id")->where('pd.id',$data['yhPolicy'])->value('p.title');
        if($data["yhPolicy"]){
            $yhpid=db("cg_channel_preferential_policy_cxfa")->where("id={$data['yhPolicy']}")->value("p_id");
            $yhnum=db("cg_channel_preferential_policy_cxfa")->where("id<={$data['yhPolicy']} and p_id=$yhpid")->count();
            $data['yhPolicymc'] = $yhtitle."-促销方案".$yhnum;
        }

        $bool = db('cg_order')->where('id',$id)->update($data);
        if($data["yhPolicy"]){
            $this-> qdyhzcxz($data["yhPolicy"],$id);
        }else{
            $this->clearyh($id);
        }
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'or']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
        die;

    }
    /**
     * 新增订单
     */
    public function xzdd(){
        $data = [];
        $data["cusType"]=2;
        $data['cusName'] = $this->request->param('net_id');
        $net=db("cg_net")->where(["id"=>$data["cusName"]])->field("id,sn,title")->find();
        if($net){
            $data["khbh"]=$net["sn"];
            $data["khmc"]=$net["title"];
        }else{
            echo json_encode(['success'=>false,'msg'=>'网点不存在','oid'=>0]);die;
        }
        $data["status"]=1;
        $data["bf_id"] = $this->request->param('bf_id');
        //$data['jxs'] = $this->request->post('jxs');
        $data['shr'] = $this->request->param('lxr');
        $data['dh'] = $this->request->param('dh');
        $data['shdz'] = $this->request->param('dz');
        $data['zysx'] = $this->request->param('bz');
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $data["sqr"]=$eid;
        $data["sqrmc"]=db("employee")->where(["id"=>$eid])->value("em_name");
        $data["sqrq"]=time();
        $data["ctime"]=time();
        $data["cuser"]=$eid;
        $data["sn"]=$this->produceodSN();
        $data["yszje"]=0;
        $data["fpType"]=1;
        $data["type_id"]=3;
        $nid=db("yd_wdbf")->where(["id"=>$data["bf_id"]])->value("wdid");
        $sid=db("cg_net")->where(["id"=>$nid])->value("system_id");
        $jid=db("cg_system")->where(["id"=>$sid])->value("jxs");
        $jfsc=db("cg_jxs")->where(["id"=>$jid])->field("zoning,provice,city")->find();
        $data["zoning"]=db("cg_market_zoning")->where(["id"=>$jfsc["zoning"]])->value("title");
        $data["provice"]=db("cg_market_provice")->where(["id"=>$jfsc["provice"]])->value("title");
        $data["city"]=db("cg_market_city")->where(["id"=>$jfsc["city"]])->value("title");
        $data["yhPolicy"]= $this->request->param('cuxiao_id');
        $yhtitle=db('cg_channel_preferential_policy p')->join("cg_channel_preferential_policy_cxfa pd","pd.p_id=p.id")->where('pd.id',$data['yhPolicy'])->value('p.title');
        if($data["yhPolicy"]){
            $yhpid=db("cg_channel_preferential_policy_cxfa")->where("id={$data['yhPolicy']}")->value("p_id");
            $yhnum=db("cg_channel_preferential_policy_cxfa")->where("id<={$data['yhPolicy']} and p_id=$yhpid")->count();
            $data['yhPolicymc'] = $yhtitle."-促销方案".$yhnum;
        }
        $bool = db('cg_order')->insertGetId($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'or','oid'=>$bool]);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error','oid'=>0]);
        }
        die;

    }
     public function produceodSN(){
        //生成编号
        $max = db('cg_order')->where('sn','like',date('Ymd').'%')->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }
    /*添加明细产品列表带默认价格*/
    public function orderprolist(){
        $nid= $this->request->param('net_id');
        $sid=db("cg_net")->where(["id"=>$nid])->value("system_id");
        $jxs_id=db("cg_system")->where(["id"=>$sid])->value("jxs");

        //查询产品订购设置
        $dgsz = db('system_param')->where(['t'=>0,'k'=>'dingDanListType'])->value('v');
        //根据经销商查询分组
        $group_id = db('price_group_jxs')->where('jid',$jxs_id)->column('gid');
        
        //查询经销商对应的渠道类型
        $qdlx = db('cg_jxs')->where('id',$jxs_id)->value('channeltype');
        //构建查询条件
        $where = [];
        if($dgsz==2){ //经销商对应的产品价格分组中的产品
            $pids = db('price_group_product')
                ->where([
                    'gid'=>['in',$group_id],
                    'start_time'=>['<=',date('Y-m-d')],
                    'end_time'=>['>=',date('Y-m-d')]
                ])
                ->column('pid');
            $where['id'] = ['in',$pids];
        }elseif($dgsz==1){ //经销商对应渠道类型的产品

            $where['channel_type'] = $qdlx;
        }
        $data = db('pro_products')->field('id,pro_name,pro_no,unit u')->where($where)->select();
        foreach($data as $k=>$v){
            $v["unit"]=2;
            if($dgsz==2){ //下单的时候只能选择该经销商所对应的产品价格分组内的产品。
                $price = db('price_group_product')
                    ->where([
                        'gid'=>['in',$group_id],
                        'pid'=>$v['id'],
                        'start_time'=>['<=',date('Y-m-d')],
                        'end_time'=>['>=',date('Y-m-d')]
                    ])
                    ->field('lingshou_price,fayun_price')->find();
                if($v["unit"]==1)
                    $v['lingshou_price'] = $price['fayun_price'];
                else
                    $v['lingshou_price'] = $price['lingshou_price'];

            }else{ //如果下单的产品在该经销商对应的价格分组中有价格，就遵循价格分组的价格。如果没有，则按照产品的标准出厂价
                $price = db('price_group_product')
                    ->where([
                        'gid'=>['in',$group_id],
                        'pid'=>$v['id'],
                        'start_time'=>['<=',date('Y-m-d')],
                        'end_time'=>['>=',date('Y-m-d')]
                    ])
                    ->field('lingshou_price,fayun_price')->find();
                if($price){
                    if($v["unit"]==1)
                        $v['lingshou_price'] = $price['fayun_price'];
                    else
                        $v['lingshou_price'] = $price['lingshou_price'];
                }else{
                    //查询产品标准价格
                    if($v["unit"]==1)
                        $bzj = db('pro_price')->where('pid',$v['id'])->value('box_factory');
                    else
                        $bzj = db('pro_price')->where('pid',$v['id'])->value('factory');
                    $v['lingshou_price'] = $bzj;
                }
            }
            if($v['unit']==1){
                $v['unit'] = '箱';
            }else{
                $v['unit'] = $v["u"];
            }
            $data[$k] = $v;
//            $v['ygj'] = db('')
        }
        echo json_encode($data);
    }
    /*订单明细详情*/
    public function ddmxdetail(){
        $did = $this->request->param('did');
        $detail=db("cg_order_list")->where(["id"=>$did])->field("id as did,product as cp_id,prod_name as pro_name,xgj as ghj,xslx,beizhu as bz")->find();
        if(!$detail){
            die;
        }
            
            $v=db("cg_order_list")->where(["id"=>$did])->field("qdyhje,dzsl,hbsl,bfje,num,order_id")->find();
            $num=$v["num"];
            if($detail["cp_id"])
            $box_num=db("pro_products")->where(["id"=>$detail["cp_id"]])->value("box_num");
            $detail["box"]=floor($num/$box_num);
            $detail["ge"]=$num-$detail["box"]*$box_num;
            $detail["unit"]=db("pro_products")->where(["id"=>$detail["cp_id"]])->value("unit");
            $str="";
            if($v["qdyhje"]){
                $str.="活动优惠金额:{$v["qdyhje"]};";
            }
            if($v["dzsl"]){
                $str.="搭赠数量:{$v["dzsl"]};";
            }
            if($v["hbsl"]){
                $str.="货补数量:{$v["hbsl"]};";
            }
            if($v["bfje"]){
                $str.="补费金额:{$v["bfje"]};";
            }
            $detail["yhms"]=$str;
            $status=db("cg_order")->where(["id"=>$v["order_id"]])->value("status");
            if($status==1){
                $detail["status"]="未处理";
            }else if($status>=2&&$status<=6){
                $detail["status"]="流程中";
            }else if($status==7){
                $detail["status"]="已通过";
            }else{
                $detail["status"]="未通过";
            }
           echo  json_encode($detail);
    }
    /*删除订单明细*/
    public function delorderdetail(){
        $id = $this->request->param('did');
        $de=db("cg_order_list")->where(["id"=>$id])->find();
        //print_r($de);exit;
        if($de["xslx"]!=1){
            echo json_encode(['success'=>false,'msg'=>'这条明细不许修改']);die;
        }
        $order_id=db("cg_order_list")->where(["id"=>$id])->value("order_id");
        if(!$order_id){
            echo json_encode(['success'=>false,'msg'=>'订单明细不存在']);die;
        }
        $order=db("cg_order")->where(["id"=>$order_id])->find();
       
        if($order["status"]!=1){
            echo json_encode(['success'=>false,'msg'=>'订单状态不允许修改']);die;
        }
        $qdyh_id=$order["yhPolicy"];
        $bool = db('cg_order_list')->where(["id"=>$id])->delete();
        if($qdyh_id){
            $this->qdyhzcxz($qdyh_id,$order_id);
        }
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'or']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
        die;
    }
    /**
     * 修改订单明细
     */
    public function xgddmx(){
        $id = $this->request->param('did');
        $de=db("cg_order_list")->where(["id"=>$id])->find();
        if($de["xslx"]!=1){
            echo json_encode(['success'=>false,'msg'=>'这条明细不许修改']);die;
        }
        $cp_id = $this->request->param('cp_id');
        
        $ghj = $this->request->param('ghj');
        $x = $this->request->param('x');
        $g = $this->request->param('g');
        $cpbz = $this->request->param('cpbz');
        
        $order_id=db("cg_order_list")->where(["id"=>$id])->value("order_id");
        if(!$order_id){
            echo json_encode(['success'=>false,'msg'=>'订单明细不存在']);die;
        }
        $order=db("cg_order")->where(["id"=>$order_id])->find();
        $product=db("pro_products")->where(["id"=>$cp_id,"is_actived"=>1,"is_deleted"=>0])->find();
        if($order["status"]!=1){
            echo json_encode(['success'=>false,'msg'=>'订单状态不允许修改']);die;
        }
        if(!$product){
            echo json_encode(['success'=>false,'msg'=>'产品不存在或已下架']);die;
        }
        $nid=$order["cusName"];
        $sid=db("cg_net")->where(["id"=>$nid])->value("system_id");
        $jxs_id=db("cg_system")->where(["id"=>$sid])->value("jxs");
        $group_id=db('price_group_jxs')->where('jid',$jxs_id)->column('gid');
        $price = db('price_group_product')
                    ->where([
                        'gid'=>['in',$group_id],
                        'pid'=>$cp_id,
                        'start_time'=>['<=',date('Y-m-d')],
                        'end_time'=>['>=',date('Y-m-d')]
                    ])
                    ->field('lingshou_price')->find();
        $qdyh_id=$order["yhPolicy"];
        $data["product"]=$cp_id;
        if(!$g)
            $g=0;
        if(!$x)
            $x=0;
        $data["beizhu"]=$cpbz;
        $data["num"]=$x*($product["box_num"])+$g;
        $data["unit"]=$product["unit"];
        $data["prod_sn"]=$product["pro_no"];
        $data["prod_name"]=$product["pro_name"];
        $sku=db("pro_sku")->where(["id"=>$product["sku_id"]])->find();
        $data["sku"]=$sku["sku_name"];
        $series=db("pro_series")->where(["id"=>$sku["series_id"]])->find();
        $data["series"]=$series["series_name"];
        $category=db("pro_category")->where(["id"=>$series["category_id"]])->find();
        $data["category"]=$category["category_name"];
        $brand=db("pro_brands")->where(["id"=>$category["brand_id"]])->find();
        $data["brand"]=$brand["brand_name"];
        if($price)
            $data["ygj"]=$price["lingshou_price"];
        else
            $data["ygj"]=db("pro_price")->where(["pid"=>$cp_id])->value("factory");
        $data["xgj"]=$ghj;
        $data["yje"]=$ghj*$data["num"];
        $data["ysje"]=$data["yje"];
        $bool = db('cg_order_list')->where(["id"=>$id])->update($data);
        if($qdyh_id){
            $this->qdyhzcxz($qdyh_id,$order_id);
        }
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'or']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
        die;

    }

    /**
     * 添加订单明细
     */
    public function tjddmx(){
        $data = [];
        $cp_id = $this->request->param('cp_id');
        $order_id = $this->request->param('order_id');
        $ghj = $this->request->param('ghj');
        $x = $this->request->param('x');
        $g = $this->request->param('g');
        $cpbz = $this->request->param('cpbz');
        $uid=$this->request->param('userid');
        //获取订单情况
        $order=db("cg_order")->where(["id"=>$order_id])->find();
        $product=db("pro_products")->where(["id"=>$cp_id,"is_actived"=>1,"is_deleted"=>0])->find();

        if(!$product){
            echo json_encode(['success'=>false,'msg'=>'产品不存在或已下架']);die;
        }
        if(!$order){
            echo json_encode(['success'=>false,'msg'=>'订单不存在']);die;
        }
        if($order["status"]>1){
            echo json_encode(['success'=>false,'msg'=>'订单状态不允许添加明细']);die;
        }

        $nid=$order["cusName"];
        $sid=db("cg_net")->where(["id"=>$nid])->value("system_id");
        $jxs_id=db("cg_system")->where(["id"=>$sid])->value("jxs");
        $group_id=db('price_group_jxs')->where('jid',$jxs_id)->column('gid');
        $price = db('price_group_product')
                    ->where([
                        'gid'=>['in',$group_id],
                        'pid'=>$cp_id,
                        'start_time'=>['<=',date('Y-m-d')],
                        'end_time'=>['>=',date('Y-m-d')]
                    ])
                    ->field('lingshou_price')->find();
        $qdyh_id=$order["yhPolicy"];
        //echo $qdyh_id;die;
        $data["kind"]=1;
        $data["product"]=$cp_id;
        if(!$g)
            $g=0;
        if(!$x)
            $x=0;
        $data["num"]=$x*($product["box_num"])+$g;
        $data["unit"]=$product["unit"];
        $data["prod_sn"]=$product["pro_no"];
        $data["prod_name"]=$product["pro_name"];
        $sku=db("pro_sku")->where(["id"=>$product["sku_id"]])->find();
        $data["sku"]=$sku["sku_name"];
        $series=db("pro_series")->where(["id"=>$sku["series_id"]])->find();
        $data["series"]=$series["series_name"];
        $category=db("pro_category")->where(["id"=>$series["category_id"]])->find();
        $data["category"]=$category["category_name"];
        $brand=db("pro_brands")->where(["id"=>$category["brand_id"]])->find();
        $data["brand"]=$brand["brand_name"];
        if($price)
            $data["ygj"]=$price["lingshou_price"];
        else
            $data["ygj"]=db("pro_price")->where(["pid"=>$cp_id])->value("factory");
        $data["xgj"]=$ghj;
        $data["yje"]=$ghj*$data["num"];
        $data["ysje"]=$data["yje"];
        $data["xsry"]=$this->geteid($uid);
        $data["beizhu"]=$cpbz;
        $data["order_id"]=$order_id;
        $data["sn"]=$this->producemxSN($order_id);
        $data["xslx"]=1;
        $bool = db('cg_order_list')->insert($data);
        if($qdyh_id){
            $this->qdyhzcxz($qdyh_id,$order_id);
        }
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'or']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
        die;

    }
     public function producemxSN($order_id){
        //生成编号
        $max = db('cg_order_list')->where(['order_id'=>$order_id])->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = 1;
        }
        return $insert_sn;
    }
    public function clearyh($oid){
        
             $bool = db('cg_order')->where('id',$oid)->update(['yhPolicy'=>0,'yhPolicymc'=>null]);
            $qdyhje = db('cg_order_list')->where(['order_id'=>$oid])->sum('qdyhje');
            db('cg_order')->where(['id'=>$oid])->setInc('yszje',$qdyhje);
           
            db('cg_order_list')->query("update cg_order_list set qdyhje=0,qdyhms=null,ysje=yje where order_id=$oid and xslx=1");
           
            db('cg_order_list')->where(['order_id'=>$oid,'sfqdzp'=>1])->delete();
            $je = db('cg_order_list')->where(['order_id'=>$oid])->sum('ysje');
            db('cg_order')->where(['id'=>$oid])->update(['yszje'=>$je]);
        
        
        
    }
     /**
     * 查询渠道优惠政策限制并计算订单金额
     */
    public function qdyhzcxz($qdyh_id,$order_id){
       // echo 1;
        $qdyh_name=db('cg_channel_preferential_policy p')->join("cg_channel_preferential_policy_cxfa pd","pd.p_id=p.id")->where('pd.id',$qdyh_id)->value('p.title');
        $qid=db("cg_channel_preferential_policy_cxfa")->where(["id"=>$qdyh_id])->value("p_id");
        $fanganno=db("cg_channel_preferential_policy_cxfa")->where("id<=$qdyh_id and p_id=$qid")->count();
        $bool = db('cg_order')
            ->where('id',$order_id)
            ->update([
                'yhPolicy'=>$qdyh_id,
                'yhPolicymc'=>$qdyh_name.'-促销方案'.$fanganno
            ]);
       //echo $bool;exit;
        //订单明细应用渠道优惠规则
        $khxx = db('cg_order')->where(['id'=>$order_id])->field('cusType,cusName')->find();
        if($khxx['cusType']==1){ //经销商
            //查询经销商所在的大区省份城市
            $jxs = $khxx['cusName'];
            $city = db('cg_jxs')->where('id',$khxx['cusName'])->value('city');
            $provice = db('cg_jxs')->where('id',$khxx['cusName'])->value('provice');
            $zoning = db('cg_jxs')->where('id',$khxx['cusName'])->value('zoning');

        }else{ //网点
            $jxs = db('cg_net t')->join('cg_system t2','t2.id=t.system_id')->where('t.id',$khxx['cusName'])->value('t2.jxs');
            $city = db('cg_jxs')->where('id',$jxs)->value('city');
            $provice = db('cg_jxs')->where('id',$jxs)->value('provice');
            $zoning = db('cg_jxs')->where('id',$jxs)->value('zoning');
        }

        //查询渠道优惠政策的明细
        $qdmx2 = Db::query('select sfzd,product,product_id,yhlx,chzk_unit,chzk_reach,chzk_down,chzk_limit,agdjch_unit,agdjch_reach,agdjch_down,agdjch_limit,shdz_unit,shdz_reach,shdz_gift,shdz_limit,shmj_unit,shmj_reach,shmj_down,shmj_limit,chfd_unit,chfd_reach,chfd_down,chfd_limit 
from cg_channel_preferential_policy_cxfa 
where id='.$qdyh_id.' 
and start <= \''.date('Y-m-d').'\' 
and `end` >=\''.date('Y-m-d').'\' 
and ((area=1 and area_id like \'%"'.$zoning.'"%\') or (area=2 and area_id like \'%"'.$provice.'"%\') or (area=3 and area_id like \'%"'.$city.'"%\')or (area=4 and area_id like \'%"'.$jxs.'"%\'))');//非整单优惠政策明细信息

        //print_r($qdmx2);exit;
        /**
         * 明细套用渠道优惠政策--start
         */
        $mx = db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>1])->select();
        $qdyhje = db('cg_order_list')->where(['order_id'=>$order_id])->sum('qdyhje');
        db('cg_order')->where(['id'=>$order_id])->setInc('yszje',$qdyhje);
       // db('cg_order_list')->where(['order_id'=>$order_id,'xslx'=>1])->update(['qdyhje'=>0,'qdyhms'=>null]);
        db('cg_order_list')->query("update cg_order_list set qdyhje=0,qdyhms=null,ysje=yje where order_id=$order_id and xslx=1");
        //echo db('cg_order_list')->getLastSql();exit;
        db('cg_order_list')->where(['order_id'=>$order_id,'sfqdzp'=>1])->delete();


        foreach($mx as $k=>$v){
            $v['id'];
            $ysje = $v['yje'];
            $ysjes=$ysje;
            //echo $ysje;exit;
            $qdyhms = '';
            $num=$v['num'];
            $v['kind']==1;
            $product = $v['product'];
            $sku = db('pro_products')->where('id',$v['product'])->value('sku_id');
            $series_id = db('pro_sku')->where('id',$sku)->value('series_id');
            $category_id = db('pro_series')->where('id',$series_id)->value('category_id');
            $brand_id = db('pro_category')->where('id',$category_id)->value('brand_id');
            foreach($qdmx2 as $k2=>$v2){
                if($v2['sfzd'] == 0){ //非整单
                    //判断产品是否符合渠道优惠政策的条件
                    if(
                        ($v2['product']==5&&in_array($product,unserialize($v2['product_id'])))
                        || ($v2['product']==1&&in_array($brand_id,unserialize($v2['product_id'])))
                        || ($v2['product']==2&&in_array($category_id,unserialize($v2['product_id'])))
                        || ($v2['product']==3&&in_array($series_id,unserialize($v2['product_id'])))
                        || ($v2['product']==4&&in_array($sku,unserialize($v2['product_id'])))
                    ){
                        if(in_array(3,unserialize($v2['yhlx']))){ //出货折扣
                            $reach = unserialize($v2['chzk_reach']);
                            $down = unserialize($v2['chzk_down']);
                            $limit = unserialize($v2['chzk_limit']);
                            $unit = $v2['chzk_unit'];
                            if($unit=='元'){
                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                   // echo $reach[$key];exit;
                                    $yhje = round($ysjes*$down[$key]/100,2);

                                    if($limit[$key]){
                                        if($yhje>$limit[$key]){
                                            $yhje = $limit[$key];
                                        }
                                    }
                                    //echo $yhje;exit;
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'元 '.$down[$key].'%OFF，限量'.$limit[$key].'元;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'元 '.$down[$key].'%OFF，限量'.$limit[$key].'元;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);
                                   
                                    $ysje = $ysje-$yhje;
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $jiannum=round($num*$down[$key]/100,2);
                                    if($limit[$key]){
                                        if($jiannum>$limit[$key]){
                                            $jiannum= $limit[$key];
                                        }
                                    }
                                    $yhje = round($jiannum*$v["xgj"],2);
                                    //echo $yhje;
                                    
                                     $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'（发运单位)'.$down[$key].'%OFF，限量'.$limit[$key].'（发运单位）;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'（发运单位)'.$down[$key].'%OFF，限量'.$limit[$key].'（发运单位）;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);

                                  
                                    $ysje = $ysje-$yhje;
                                }
                            }
                        }

                        if(in_array(4,unserialize($v2['yhlx']))){ //按固定价出货
                            $reach = unserialize($v2['agdjch_reach']);
                            $down = unserialize($v2['agdjch_down']);
                            $limit = unserialize($v2['agdjch_limit']);
                            $unit = $v2['agdjch_unit'];
                            if($unit=='元'){
                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $yhje = $num*$down[$key];
                                    $sxje = $ysje-$yhje; //省下金额
                                    //echo $sxje;exit;
                                    if($limit[$key]){
                                         if($sxje>$limit[$key]){
                                            $sxje = $limit[$key];
                                        }
                                    }
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'元按'.$down[$key].'元出货，限量'.$limit[$key].'元;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'元按'.$down[$key].'元出货，限量'.$limit[$key].'元;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$sxje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$sxje);

                                   
                                    $ysje = $ysje-$sxje;
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    //echo $limit[$key];
                                    $limit[$key];
                                    if($limit[$key]){
                                        if($num>$limit[$key]){
                                            $sxje = ($v['xgj']-$down[$key])*$limit[$key];
                                        }else{ //完全按照新价格计算优惠金额
                                            $yhje = $num*$down[$key];
                                            $sxje = $ysjes-$yhje; //省下金额

                                        }
                                    }else{
                                        $yhje = $num*$down[$key];
                                        $sxje = $ysjes-$yhje; //省下金额
                                    }
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'（发运单位）按'.$down[$key].'（元/发运单位）出货，限量'.$limit[$key].'（发运单位）;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'（发运单位）按'.$down[$key].'（元/发运单位）出货，限量'.$limit[$key].'（发运单位）;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$sxje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$sxje);


                                    $ysje = $ysje-$sxje;
                                }
                            }
                        }

                        if(in_array(5,unserialize($v2['yhlx']))){ //随货搭赠
                            //echo 5;
                            $reach = unserialize($v2['shdz_reach']);
                            $down = unserialize($v2['shdz_gift']);
                            $limit = unserialize($v2['shdz_limit']);
                            $unit = $v2['shdz_unit'];
                            if($unit=='元'){

                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $gift = $this->unescape($down[$key]);
//                                $gift = str_replace('"',"'",$gift);

                                    $gift = json_decode($gift);
                                    $zongbujin=0;

                                    foreach ($gift as $gk => $gv) {
                                        # code...
                                        $zongbujin+=$gv->total;
                                    }
                                    $buhuojine=round($ysjes/$reach[$key],2)*$zongbujin;
                                    if($limit[$key]){
                                        $buhuojine=$buhuojine<=$limit[$key]?$buhuojine:$limit[$key];
                                    }
                                    $beishu=round($buhuojine/$zongbujin,2);
                                    //echo $beishu;//exit;
                                    $zj = 0;
                                    foreach($gift as $gk => $gv){
                                       // echo 1;
                                        $ins = [];
                                        $ins['kind'] = $gv->wy+1;

                                        $ins['product'] = $gv->product;

                                        if($gv->wy==0){
                                            $ins['prod_sn'] = db('pro_products')->where('id',$gv->product)->value('pro_no');
                                            $ins['sku'] = db('pro_products')->where('id',$gv->product)->value('sku_id');
                                            $ins['series'] = db('pro_sku')->where('id',$ins['sku'])->value('series_id');
                                            $ins['category'] = db('pro_series')->where('id',$ins['series'])->value('category_id');
                                            $ins['brand'] = db('pro_category')->where('id',$ins['category'])->value('brand_id');
                                        }else{
                                            $ins['prod_sn'] = db('pro_materials')->where('id',$gv->product)->value('material_no');
                                        }

                                        $ins['prod_name'] = $gv->product_title;
                                        $ins['dzsl'] = floor($gv->num*$beishu);
                                        $ins['unit'] = $gv->unit;
                                        $ins['ygj'] = $gv->price;
                                        $ins['xgj'] = $gv->price;
                                        $ins['yje'] = floor($gv->num*$beishu)*$gv->price;
                                        $ins['order_id'] = $v['order_id'];
                                        $ins['dyddmxid'] = $v['id'];
                                        $ins['xslx'] = 2;
                                        $ins['ysje'] = 0;
                                        $ins['sfqdzp'] = 1;
                                        $ins['sn'] = $this->producemxSN($v['order_id']);

                                        $zj += $ins['yje'];
                                        if($limit[$key]){
                                            if($zj>$limit[$key]){
                                                continue;
                                            }
                                        }
                                        

                                        db('cg_order_list')->insert($ins);
                                    }
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $gift = $this->unescape($down[$key]);

                                    $gift = json_decode($gift);
                                    $jiannum=$num;
                                    if($limit[$key]){
                                        $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                    }
                                    $beishu=floor($jiannum/$reach[$key]);
                                    //echo $beishu;
                                    $zj = 0;
                                    foreach($gift as $gk => $gv){
                                        $ins['kind'] = $gv->wy+1;

                                        $ins['product'] = $gv->product;
                                        if($gv->wy==0){
                                            $ins['prod_sn'] = db('pro_products')->where('id',$gv->product)->value('pro_no');
                                            $ins['sku'] = db('pro_products')->where('id',$gv->product)->value('sku_id');
                                            $ins['series'] = db('pro_sku')->where('id',$ins['sku'])->value('series_id');
                                            $ins['category'] = db('pro_series')->where('id',$ins['series'])->value('category_id');
                                            $ins['brand'] = db('pro_category')->where('id',$ins['category'])->value('brand_id');
                                        }else{
                                            $ins['prod_sn'] = db('pro_materials')->where('id',$gv->product)->value('material_no');
                                        }

                                        $ins['prod_name'] = $gv->product_title;
                                        $ins['dzsl'] = $gv->num*$beishu;
                                        $ins['unit'] = $gv->unit;
                                        $ins['ygj'] = $gv->price;
                                        $ins['xgj'] = $gv->price;
                                        $ins['yje'] = $gv->total*$beishu;
                                        $ins['order_id'] = $v['order_id'];
                                        $ins['dyddmxid'] = $v['id'];
                                        $ins['xslx'] = 2;
                                        $ins['ysje'] = 0;
                                        $ins['sfqdzp'] = 1;
                                        $ins['sn'] = $this->producemxSN($v['order_id']);
                                        $zj += $ins['yje'];
                                        
                                        db('cg_order_list')->insert($ins);
                                    }

                                }
                            }
                        }

                        if(in_array(1,unserialize($v2['yhlx']))){ //随货满减
                            
                            $reach = unserialize($v2['shmj_reach']);
                            $down = unserialize($v2['shmj_down']);
                            $limit = unserialize($v2['shmj_limit']);
                            $unit = $v2['shmj_unit'];
                            if($unit=='元'){
                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $jianjine=floor($ysjes/$reach[$key])*$down[$key];
                                    //echo $jianjine;exit;
                                    if($limit[$key]){
                                        $jianjine=$jianjine<=$limit[$key]?$jianjine:$limit[$key];
                                    }
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'元，限量'.$limit[$key].'元;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'元，限量'.$limit[$key].'元;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$jianjine);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$jianjine);


                                    $ysje = $ysje-$jianjine;
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $jiannum=floor($num/$reach[$key])*$down[$key];

                                    if($limit[$key]){
                                        $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                    }
                                    //echo $jiannum;exit;
                                    $jian =$jiannum*$v['xgj'];
                                     $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'(发运单位) 减'.$down[$key].'(发运单位)，限量'.$limit[$key].'(发运单位);';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'(发运单位) 减'.$down[$key].'(发运单位)，限量'.$limit[$key].'(发运单位);';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$jian);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$jian);

                                    
                                    $ysje = $ysje-$jian;
                                }
                            }
                        }

                        if(in_array(2,unserialize($v2['yhlx']))){ //出货返点

                            $reach = unserialize($v2['chfd_reach']);
                            $down = unserialize($v2['chfd_down']);
                            $limit = unserialize($v2['chfd_limit']);
                            $unit = $v2['chfd_unit'];
                            if($unit=='元'){
                                $max = $this->jstj($reach,$ysjes);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                    $yhje = round($ysjes*$down[$key]/100,2);
                                    if($limit[$key]){
                                        if($yhje>$limit[$key]){
                                            $yhje = $limit[$key];
                                        }
                                    }
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'%，限量'.$limit[$key].'元;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'%，限量'.$limit[$key].'元;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);

                                    $ysje = $ysje-$yhje;
                                }
                            }else{ //发运单位
                                $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                                if($max){
                                    $key=array_search($max ,$reach);
                                    $down[$key];
                                    $limit[$key];
                                   $jiannum=round($num*$down[$key]/100,2);
                                    //echo $jiannum;exit;
                                    if($limit[$key]){
                                        $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                    }
                                    
                                    $yhje =$jiannum*$v['xgj'];
                                    $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                    if($qdms){
                                        $qdms.=$qdyhms.'满'.$reach[$key].'（发运单位) 减'.$down[$key].'%，限量'.$limit[$key].'（发运单位）;';
                                    }else{
                                        $qdms=$qdyhms.'满'.$reach[$key].'（发运单位) 减'.$down[$key].'%，限量'.$limit[$key].'（发运单位）;';
                                    }
                                    db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                    db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);

                                    
                                    $ysje = $ysje-$yhje;
                                }
                            }
                        }
                        $qdyhzcje = db('cg_order_list')->where('order_id',$v['order_id'])->sum('qdyhje');
                        db('cg_order')
                            ->where('id',$v['order_id'])
                            ->setDec('yszje',$qdyhzcje);
                    }
                }else{ //整单
                    //echo 1;
                    if(in_array(1,unserialize($v2['yhlx']))){ //随货满减

                        $reach = unserialize($v2['shmj_reach']);
                        $down = unserialize($v2['shmj_down']);
                        $limit = unserialize($v2['shmj_limit']);
                        $unit = $v2['shmj_unit'];//echo $ysje;exit;
                       // echo 1;exit;
                        if($unit=='元'){
                            $max = $this->jstj($reach,$ysjes);

                            if($max){
                                $key=array_search($max ,$reach);
                                $down[$key];
                                $limit[$key];

                                $jisuanjine=floor($ysjes/$reach[$key])*$down[$key];
                                if($limit[$key])
                                    $jisuanjine=$jisuanjine<=$limit[$key]?$jisuanjine:$limit[$key];
                                //echo $jisuanjine;exit;
                                $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                if($qdms){
                                    $qdms.=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'元，限量'.$limit[$key].'元;';
                                }else{
                                    $qdms=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'元，限量'.$limit[$key].'元;';
                                }

                                db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                               
                                db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$jisuanjine);
                                db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$jisuanjine);
                                $ysje = $ysje-$jisuanjine;
                            }
                        }else{ //发运单位
                            echo 1;
                            $max = $this->jstj2($reach,$ysjes,$v['xgj']);

                            if($max){
                                $key=array_search($max ,$reach);
                                $down[$key];
                                $limit[$key];
                                $jiannum=floor($num/$reach[$key])*$down[$key];

                                if($limit[$key]){
                                    $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                }
                                //echo $jiannum;exit;
                                $jian =$jiannum*$v['xgj'];
                               //echo $jian.'|';
                                $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                if($qdms){
                                    $qdms.=$qdyhms.'满'.$reach[$key].'(发运单位) 减'.$down[$key].'(发运单位)，限量'.$limit[$key].'(发运单位);';
                                }else{
                                    $qdms=$qdyhms.'满'.$reach[$key].'(发运单位) 减'.$down[$key].'(发运单位)，限量'.$limit[$key].'(发运单位);';
                                }
                                db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$jian);
                                db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$jian);

                                $ysje = $ysje-$jian;
                            }
                        }
                    }

                    if(in_array(2,unserialize($v2['yhlx']))){ //出货返点
                        
                        $reach = unserialize($v2['chfd_reach']);
                        $down = unserialize($v2['chfd_down']);
                        $limit = unserialize($v2['chfd_limit']);
                        $unit = $v2['chfd_unit'];
                        //echo $ysje;exit;
                        //echo 2;exit;
                        if($unit=='元'){
                            $max = $this->jstj($reach,$ysjes);

                            if($max){
                                $key=array_search($max ,$reach);
                                $down[$key];
                                $limit[$key];
                                $yhje = round($ysjes*$down[$key]/100,2);
                                //echo $yhje;exit;
                                if($limit[$key]){
                                    if($yhje>$limit[$key]){
                                        $yhje = $limit[$key];
                                    }
                                }
                                $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                if($qdms){
                                    $qdms.=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'%，限量'.$limit[$key].'元;';
                                }else{
                                    $qdms=$qdyhms.'满'.$reach[$key].'元 减'.$down[$key].'%，限量'.$limit[$key].'元;';
                                }

                                db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                //echo $yhje;exit;
                                db('cg_order_list')->where("id={$v["id"]}")->setInc('qdyhje',$yhje);//echo 1;exit;

                                db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);
                                $ysje = $ysje-$yhje;
                            }
                        }else{ //发运单位

                            $max = $this->jstj2($reach,$ysjes,$v['xgj']);
                            //echo $max;exit;
                            if($max){

                                $key=array_search($max ,$reach);

                                $down[$key];
                                $limit[$key];
                                $jiannum=round($num*$down[$key]/100,2);
                                //echo $jiannum;exit;
                                if($limit[$key]){
                                    $jiannum=$jiannum<=$limit[$key]?$jiannum:$limit[$key];
                                }
                                
                                $yhje =$jiannum*$v['xgj'];
                                //echo $yhje.'|';
                                $qdms=db('cg_order_list')->where(['id'=>$v['id']])->value("qdyhms");
                                if($qdms){
                                    $qdms.=$qdyhms.'满'.$reach[$key].'（发运单位) 减'.$down[$key].'%，限量'.$limit[$key].'（发运单位）;';
                                }else{
                                    $qdms=$qdyhms.'满'.$reach[$key].'（发运单位) 减'.$down[$key].'%，限量'.$limit[$key].'（发运单位）;';
                                }
                                 db('cg_order_list')->where(['id'=>$v['id']])->update(['qdyhms'=>$qdms]);
                                db('cg_order_list')->where(['id'=>$v['id']])->setInc('qdyhje',$yhje);
                                db('cg_order_list')->where(['id'=>$v['id']])->setDec("ysje",$yhje);
                                $ysje = $ysje-$yhje;
                            }
                        }
                    }

                    $qdyhzcje = db('cg_order_list')->where('order_id',$v['order_id'])->sum('qdyhje');
                    $oid=$v["order_id"];
                    $je = db('cg_order_list')->where(['order_id'=>$oid])->sum('ysje');
            db('cg_order')->where(['id'=>$oid])->update(['yszje'=>$je]);
                }

            }
        }
       
    }
     //计算最大满数
    public function jstj($chzk_reach,$ysje){
        if(count($chzk_reach)==0){
            return false;
        }else{
            $max = max($chzk_reach);

            if($ysje>=$max){
                return $max;
            }else{
                $key=array_search($max ,$chzk_reach);
                array_splice($chzk_reach,$key,1);
                $this->jstj($chzk_reach,$ysje);
            }
        }
    }
    //计算最大满数--按照发运单位
    /**
     * @param $chzk_reach
     * @param $ysje
     * @param $xgj
     * @return bool|mixed
     */
    public function jstj2($chzk_reach,$ysje,$xgj){
        if(count($chzk_reach)==0){
            return false;
        }else{
            $max = max($chzk_reach);

            if($ysje>=$max*$xgj){
                return $max;
            }else{
                $key=array_search($max ,$chzk_reach);
                array_splice($chzk_reach,$key,1);
                $this->jstj($chzk_reach,$ysje,$xgj);
            }
        }
    }
    /**
     * 删除订单
     */
    public function scdd(){
        $id = $this->request->param('oid');
        $order=db("cg_order")->where(["id"=>$id])->find();
        if(!$order){
            echo json_encode(['success'=>false,'msg'=>'订单不存在']);die;
        }
        if($order["status"]!=1){
            echo json_encode(['success'=>false,'msg'=>'订单状态已不允许删除']);die;
        }
        $bool = db('cg_order')->where('id',$id)->delete();
        $bool2 = db('cg_order_list')->where('order_id',$id)->delete();
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'or']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
        die;
    }

   

    
    
    /**
     * 添加竞品汇报
     */
    public function tjjphb(){
        $data = [];
        //$data['net_id'] = $this->request->param('net_id');
        $data['jp_id'] = $this->request->param('jp_id');
        $data['jpgg'] = $this->request->param('jpgg');
        $data['lsj'] = $this->request->param('lsj');
        $data['sfcx'] = $this->request->param('sfcx');
        $data['jpms'] = $this->request->param('jpms');
        $data['sczp'] = $this->request->param('sczp');
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $data['hbr'] = $eid;
        $data["day"]=date("Y-m-d");
        $data["bf_id"]= $this->request->param('bf_id');
        $bf=db("yd_wdbf")->where(["id"=>$data["bf_id"]])->find();
        if(!$bf){
            echo json_encode(['success'=>false,'msg'=>'拜访不存在']);die;
        }
        $data["net_id"]=$bf["wdid"];
        $bool = db('yd_jphb')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    /**
     * 竞品汇报修改
     */
    public function xgjphb(){
        $id = $this->request->param('id');
        $data['jp_id'] = $this->request->param('jp_id');
        $data['jpgg'] = $this->request->param('jpgg');
        $data['lsj'] = $this->request->param('lsj');
        $data['sfcx'] = $this->request->param('sfcx');
        $data['jpms'] = $this->request->param('jpms');
        $data['sczp'] = $this->request->param('sczp');
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $data['hbr'] = $eid;
        $data["day"]=date("Y-m-d");
        $bool = db('yd_jphb')->where(["id"=>$id])->update($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    /**
     * 竞品汇报列表
     */
    public function jphb(){
        $id = $this->request->param('id');
        $bf_id=$this->request->param('bf_id');
        //$page = $this->request->param('page')?$this->request->param('page'):1;
        $dgs = db('yd_jphb')->where(['bf_id'=>$bf_id])->order("day desc")->select();
        $dg=[];
        foreach ($dgs as $k => $v) {
            # code...
            $dg[$k]=$v;
            $dg[$k]["competitor"]=db("competitor")->where(["id"=>$v["jp_id"]])->value("c_name");
            $dg[$k]["category_id"]=db("competitor")->where(["id"=>$v["jp_id"]])->value("category_id");
            $dg[$k]["category"]=db("competitor_category")->where(["id"=>$dg[$k]["category_id"]])->value("category_name");
        }
        echo json_encode($dg);
    }
    /*
    竞品汇报明细

     */
    public function jphbmx(){
        $id = $this->request->param('id');

        //$page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('yd_jphb')->where(['id'=>$id])->find();
       
        $dg["competitor"]=db("competitor")->where(["id"=>$dg["jp_id"]])->value("c_name");
        $dg["category_id"]=db("competitor")->where(["id"=>$dg["jp_id"]])->value("category_id");
        $dg["category"]=db("competitor_category")->where(["id"=>$dg["category_id"]])->value("category_name");
        echo json_encode($dg);
    }
    /**
     * 添加网点拜访小结
     */
    public function wdbfxj(){
        $data = [];
        //$data['net_id'] = $this->request->param('net_id');
        $bf_id = $this->request->param('bf_id');
        
        $data['bcpfxj'] = $this->request->param('bcpfxj');
        $data['xcpfrq'] = $this->request->param('xcpfrq');
        $data['xcpfmb'] = $this->request->param('xcpfmb');
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $data['hbr'] = $eid;
        $data['hbrq']=date("Y-m-d");
        $ishas=db('yd_wdbfxj')->where(["bf_id"=>$bf_id])->find();
        if($ishas){
            //存在修改
            $bool = db('yd_wdbfxj')->where(["bf_id"=>$bf_id])->update($data);
        }else{
            //新增
            $data["bf_id"]=$bf_id;
            $bool = db('yd_wdbfxj')->insert($data);
        }
        
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    /*
        网点拜访小结内容

     */
    public function wdbfnr(){
        $bf_id = $this->request->param('bf_id');
        $data=db('yd_wdbfxj')->where(["bf_id"=>$bf_id])->field("bcpfxj,xcpfrq,xcpfmb")->find();
        echo json_encode($data);
    }
    /**
     * 离店签退
     */
    public function ldqt(){
        $bf_id = $this->request->param('bf_id');
        $data = [];
        $ishas=db('yd_wdbf')->where(['id'=>$bf_id])->find();
        if($ishas){
            if($ishas["ldsj"]){
                echo json_encode(['success'=>true,'msg'=>'您不能重复签退']);
            }else{
                 $data['qtdd'] = $this->request->param('qtdd');
                if($data["qtdd"]){
                    $data['ldtp'] = $this->request->param('ldtp');
                    $data['ldsj'] = date("Y-m-d H:i:s");
                    $ddsj = db('yd_wdbf')->where(['id'=>$bf_id])->value('ddsj');
                    $data['ys'] = round((strtotime($data['ldsj']) - strtotime($ddsj))/60,2);
                    $bool = db('yd_wdbf')->where(['id'=>$bf_id])->update($data);
                    if(false!==$bool){
                        echo json_encode(['success'=>true,'msg'=>'ok']);
                    }else{
                        echo json_encode(['success'=>false,'msg'=>'error']);
                    }
                }else{
                    echo json_encode(['success'=>false,'msg'=>'签退地点不能为空']);
                }
                
            }
            
           
        }else{
            echo json_encode(['success'=>false,'msg'=>'拜访不存在']);
        }
        
    }
    /*
    离店签退信息
     */
    public function ldqtnr(){
        $bf_id = $this->request->param('bf_id');
        $ishas=db('yd_wdbf')->where(['id'=>$bf_id])->find();
        if($ishas){
            if($ishas["ldsj"]){
                echo json_encode(['success'=>true,'isqt'=>1,'msg'=>'已签退','qtdd'=>$ishas['qtdd'],'qtsj'=>$ishas['ldsj'],'ldtp'=>$ishas["ldtp"]]);
            }else{
                echo json_encode(['success'=>true,'isqt'=>0,'msg'=>'未签退']);
            }
        }else{
            echo json_encode(['success'=>false,'isqt'=>0,'msg'=>'拜访不存在']);
        }
    }
     /*历史活动*/
    public function lishihuodong(){
        $wdmc = $this->request->param('wdmc');
        $where = "t.status=7 and (t.status2 is null or t.status2=0) and td.net_id>0 and t.type_id<>1 ";
        if($wdmc){
            $nid=db("cg_net")->where("title like '%$wdmc%'")->field("id")->select();
            $narr=[];
            if($nid){
                foreach ($nid as $k => $v) {
                    # code...
                    $narr[]=$v["id"];
                }
                $nids=implode(',',$narr);
                $where.="and td.net_id in ($nids) ";
            }else{
                $where.="and 1<>1 ";
            }
            
        }
        $now=time();
         $where.="and td.end<$now ";
         $dgs=db("cg_ti t")->join("cg_ti_list td","td.ti_id=t.id")->join("cg_net n","td.net_id=n.id")->where($where)->field("td.id,td.start,td.end,td.brand,td.category,td.series,td.sku,td.product,td.feetype,t.sn tsn,td.sn tdsn,t.type_id,hc_stauts")->select();
         $dg=[];
        foreach ($dgs as $k => $v) {
            # code...
            $dg[$k]["id"]=$v["id"];
            $dg[$k]["feetype"]=db("cg_feiyongkemu3")->where(["id"=>$v["feetype"]])->value("title");
            $dg[$k]["start"]=date("Y-m-d",$v["start"]);
            $dg[$k]["end"]=date("Y-m-d",$v["end"]);
            if($v["brand"]){
                $dg[$k]["pro_type"]="品牌";
                $dg[$k]["pro"]=db("pro_brands")->where(["id"=>$v["brand"]])->value("brand_name");
            }
            if($v["category"]){
                $dg[$k]["pro_type"]="品类";
                $dg[$k]["pro"]=db("pro_category")->where(["id"=>$v["category"]])->value("category_name");
            }
            if($v["series"]){
                $dg[$k]["pro_type"]="系列";
                $dg[$k]["pro"]=db("pro_series")->where(["id"=>$v["series"]])->value("series_name");
            }
            if($v["sku"]){
                $dg[$k]["pro_type"]="sku";
                $dg[$k]["pro"]=db("pro_sku")->where(["id"=>$v["sku"]])->value("sku_name");
            }
            if($v["product"]){
                $dg[$k]["pro_type"]="产品";
                $dg[$k]["pro"]=db("pro_products")->where(["id"=>$v["product"]])->value("pro_name");
            }
            $dg[$k]["sn"]=$v["tsn"].'-'.$v["tdsn"];
            if($v["type_id"]==0)
                $dg[$k]["type"]="非常规促销";
            else if($v["type_id"]==2)
                $dg[$k]["type"]="常规促销";
            else if($v["type_id"]==3)
                $dg[$k]["type"]="TPM费用申请";
            else if($v["type_id"]==1)
                $dg[$k]["type"]="进场费用";
            $dg[$k]["hc_stauts"]=$v["hc_stauts"];
        }
        echo json_encode($dg);
    }
    /**
     * 市场活动拜访-本期活动列表
     */
    public function schdbf_wdlb(){
        $wdmc = $this->request->param('wdmc');
        $type = $this->request->param('type');
        $where = "t.status=7 and (t.status2 is null or t.status2=0) and td.net_id>0 and t.type_id<>1 ";
        if($wdmc){
            $nid=db("cg_net")->where("title like '%$wdmc%'")->field("id")->select();
            $narr=[];
            if($nid){
                foreach ($nid as $k => $v) {
                    # code...
                    $narr[]=$v["id"];
                }
                $nids=implode(',',$narr);
                $where.="and td.net_id in ($nids) ";
            }else{
                $where.="and 1<>1 ";
            }
            
        }
        if(!$type)
            $type=1;
        $now=time();
        if($type==1){
            $where.="and td.start<=$now and td.end>=$now ";
        }else if($type==2){
            $where.="and td.start>$now ";
        }
        $dg=db("cg_ti t")->join("cg_ti_list td","td.ti_id=t.id")->join("cg_net n","td.net_id=n.id")->where($where)->group("td.net_id")->field("n.title,n.sn,n.id,n.detailAddress as addr")->select();

       
        
        echo json_encode($dg);
    }

    /**
     * 市场活动拜访-活动列表
     */
    public function schdbf_bqhd(){
        $id = $this->request->param('id');
        $type = $this->request->param('type');

        $where = "t.status=7 and (t.status2 is null or t.status2=0) and td.net_id=$id and t.type_id<>1 ";
        if(!$type)
            $type=1;
        $now=time();
        if($type==1){
            $where.="and td.start<=$now and td.end>=$now ";
        }else if($type==2){
            $where.="and td.start>$now ";
        }

        $dgs=db("cg_ti t")->join("cg_ti_list td","td.ti_id=t.id")->join("cg_net n","td.net_id=n.id")->where($where)->field("td.id,td.start,td.end,td.brand,td.category,td.series,td.sku,td.product,td.feetype,t.type_id,td.hc_stauts,t.sn as tsn,td.sn as tdsn")->select();
        $dg=[];
        foreach ($dgs as $k => $v) {
            # code...
            $dg[$k]["id"]=$v["id"];
            $dg[$k]["feetype"]=db("cg_feiyongkemu3")->where(["id"=>$v["feetype"]])->value("title");
            $dg[$k]["start"]=date("Y-m-d",$v["start"]);
            $dg[$k]["end"]=date("Y-m-d",$v["end"]);
            if($v["brand"]){
                $dg[$k]["pro_type"]="品牌";
                $dg[$k]["pro"]=db("pro_brands")->where(["id"=>$v["brand"]])->value("brand_name");
            }
            if($v["category"]){
                $dg[$k]["pro_type"]="品类";
                $dg[$k]["pro"]=db("pro_category")->where(["id"=>$v["category"]])->value("category_name");
            }
            if($v["series"]){
                $dg[$k]["pro_type"]="系列";
                $dg[$k]["pro"]=db("pro_series")->where(["id"=>$v["series"]])->value("series_name");
            }
            if($v["sku"]){
                $dg[$k]["pro_type"]="sku";
                $dg[$k]["pro"]=db("pro_sku")->where(["id"=>$v["sku"]])->value("sku_name");
            }
            if($v["product"]){
                $dg[$k]["pro_type"]="产品";
                $dg[$k]["pro"]=db("pro_products")->where(["id"=>$v["product"]])->value("pro_name");
            }
            if($v["type_id"]==0)
                $dg[$k]["type"]="非常规促销";
            else if($v["type_id"]==2)
                $dg[$k]["type"]="常规促销";
            else if($v["type_id"]==3)
                $dg[$k]["type"]="TPM费用申请";
            else if($v["type_id"]==1)
                $dg[$k]["type"]="进场费用";
            $dg[$k]["hc_stauts"]=$v["hc_stauts"];
            $dg[$k]["sn"]=$v["tsn"].'-'.$v["tdsn"];
        }
        echo json_encode($dg);
    }
      /*所属市场活动汇报*/
    public function suoshuhuibao(){
        $type = $this->request->param('type');
        //1未汇报  2已汇报
        $uid= $this->request->param('userid');
        $eid=$this->geteid($uid);
        if(!$type)
            $type=1;
        $netarr=db("yd_schdbf")->where(["hbzt"=>$type,"hbr"=>$eid])->order("id desc")->limit(0,50)->select();
        $data=[];
        foreach ($netarr as $k => $v) {
            # code...
            $nid=$v["net_id"];
            $net=db("cg_net")->where(["id"=>$nid])->find();
            $data[$k]["id"]=$v["id"];
            $data[$k]["net"]=$net["title"];
            $data[$k]["net_sn"]=$net["sn"];
            $data[$k]["addr"]=$net["detailAddress"];
            $hd=db("cg_ti t")->join("cg_ti_list td","td.ti_id=t.id")->where(["td.id"=>$v["de_id"]])->field("t.sn tsn,td.sn tdsn,td.start,td.end,td.brand,td.category,td.series,td.sku,td.product,td.feetype")->find();
            $data[$k]["hd_sn"]=$hd["tsn"].'-'.$hd["tdsn"];
            $data[$k]["start"]=date("Y-m-d",$hd["start"]);
            $data[$k]["end"]=date("Y-m-d",$hd["end"]);
            $data[$k]["feetype"]=db("cg_feiyongkemu3")->where(["id"=>$hd["feetype"]])->value("title");
            if($hd["brand"]){
                $data[$k]["pro_type"]="品牌";
                $data[$k]["pro"]=db("pro_brands")->where(["id"=>$hd["brand"]])->value("brand_name");
            }
            if($hd["category"]){
                $data[$k]["pro_type"]="品类";
                $data[$k]["pro"]=db("pro_category")->where(["id"=>$hd["category"]])->value("category_name");
            }
            if($hd["series"]){
                $data[$k]["pro_type"]="系列";
                $data[$k]["pro"]=db("pro_series")->where(["id"=>$hd["series"]])->value("series_name");
            }
            if($hd["sku"]){
                $data[$k]["pro_type"]="sku";
                $data[$k]["pro"]=db("pro_sku")->where(["id"=>$hd["sku"]])->value("sku_name");
            }
            if($hd["product"]){
                $data[$k]["pro_type"]="产品";
                $data[$k]["pro"]=db("pro_products")->where(["id"=>$hd["product"]])->value("pro_name");
            }
            $stuff=unserialize($net["stuff"]);
            if($stuff){
                $stuff=implode(',',$stuff);
                $em=db("employee")->where("id in ($stuff)")->field("em_name")->select();
                $ems=[];
                foreach ($em as $ke => $ve) {
                    # code...
                    $ems[]=$ve["em_name"];
                }
                $data[$k]["yewuyuan"]=implode(',',$ems);
            }else{
                $data[$k]["yewuyuan"]="";
            }
            $dg=db("cg_net_dg")->where(["net_id"=>$v["net_id"]])->field("xm")->select();
            $dgs=[];
            foreach ($dg as $kd => $vd) {
                # code...
                $dgs[]=$vd["xm"];
            }
            $data[$k]["daogou"]=implode(',',$dgs);
            $data[$k]["hbrq"]=$v["hbrq"];
            $data[$k]["hbr"]=db("employee")->where(["id"=>$v["hbr"]])->value("em_name");
        }
        echo json_encode($data);
    }
    public function suoshuhuibaoxq(){
        $bf_id=$this->request->param('bf_id');
        $bf=db("yd_schdbf")->where(["id"=>$bf_id])->find();
        $nid=$bf["net_id"];
        $did=$bf["de_id"];
        $hd=db("cg_ti t")->join("cg_ti_list td","td.ti_id=t.id")->where("td.id in ($did)")->field("td.id,t.sn tsn,td.sn tdsn,td.start,td.end,td.brand,td.category,td.series,td.sku,td.product,td.feetype,t.type_id,td.hc_stauts")->select();
        $data=[];
        foreach ($hd as $k => $v) {
            # code...
            $data[$k]["hd_id"]=$v["id"];
            $data[$k]["hd_sn"]=$v["tsn"].'-'.$v["tdsn"];
            $data[$k]["start"]=date("Y-m-d",$v["start"]);
            $data[$k]["end"]=date("Y-m-d",$v["end"]);
            $data[$k]["feetype"]=db("cg_feiyongkemu3")->where(["id"=>$v["feetype"]])->value("title");
            if($v["brand"]){
                $data[$k]["pro_type"]="品牌";
                $data[$k]["pro"]=db("pro_brands")->where(["id"=>$v["brand"]])->value("brand_name");
            }
            if($v["category"]){
                $data[$k]["pro_type"]="品类";
                $data[$k]["pro"]=db("pro_category")->where(["id"=>$v["category"]])->value("category_name");
            }
            if($v["series"]){
                $data[$k]["pro_type"]="系列";
                $data[$k]["pro"]=db("pro_series")->where(["id"=>$v["series"]])->value("series_name");
            }
            if($v["sku"]){
                $data[$k]["pro_type"]="sku";
                $data[$k]["pro"]=db("pro_sku")->where(["id"=>$v["sku"]])->value("sku_name");
            }
            if($v["product"]){
                $data[$k]["pro_type"]="产品";
                $data[$k]["pro"]=db("pro_products")->where(["id"=>$v["product"]])->value("pro_name");
            }
            if($v["type_id"]==0){
                $data[$k]["type"]="非常规促销";
            }else if($v["type_id"]==2){
                $data[$k]["type"]="常规促销";
            }else if($v["type_id"]==3){
                $data[$k]["type"]="TPM活动";
            }else{
                $data[$k]["type"]="进场";
            }
            $data[$k]["hc_stauts"]=$v["hc_stauts"];
        }
        echo json_encode($data);
        
    }
    /*活动核减列表*/
    public function hdhjlist(){
        $bf_id=$this->request->param('bf_id');
        $hd_id=$this->request->param('hd_id');
        $hj=db("yd_schdhj")->where(["de_id"=>$hd_id])->select();
        $data=[];
        foreach ($hj as $k => $v) {
            # code...
            $data[$k]["id"]=$v["id"];
            $data[$k]["hbr"]=db("employee")->where(["id"=>$v["hbr"]])->value("em_name");
            $data[$k]["jyhx"]=$v["jyhx"];
            $data[$k]["addr"]=$v["addr"];
            $data[$k]["hdms"]=$v["hdms"];
            $data[$k]["zp"]=$v["zp"];
            if($bf_id==$v["bf_id"]){
                $data[$k]["isthis"]=1;
            }else{
                $data[$k]["isthis"]=0;
            }
            $data[$k]["hbtime"]=$v["hbtime"];
        }
        echo json_encode($data);
    }
    /*添加活动核减*/
    public function addhj(){
        $bf_id=$this->request->param('bf_id');
        $hd_id=$this->request->param('hd_id');
        $uid=$this->request->param('userid');
        $jyhx=$this->request->param('jyhx');
        $addr=$this->request->param('addr');
        $hdms=$this->request->param('hdms');
        $zp=$this->request->param('zp');
        if(!$hdms){
            echo json_encode(['success'=>false,'msg'=>'活动描述不能为空']);die;
        }
        if($bf_id&&$hd_id&&$uid){
            $data["bf_id"]=$bf_id;
            $data["de_id"]=$hd_id;
            $data["jyhx"]=$jyhx;
            $data["hdms"]=$hdms;
            $data["addr"]=$addr;
            $data["zp"]=$zp;
            $data["hbr"]=$this->geteid($uid);
            $data["hbtime"]=date("Y-m-d H:i:s");
            $bool = db('yd_schdhj')->insert($data);
            db("yd_schdbf")->where(["id"=>$bf_id])->update(["hbzt"=>2]);
            if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
        }else{
            echo json_encode(['success'=>false,'msg'=>'请正确提交']);die;
        }
       
    }
    /**
     * 添加市场活动拜访
     */
    public function xzsjhdbf(){
        $data = [];
        $data["de_id"]=$this->request->param('de_id');
        $data["net_id"]=db("cg_ti_list")->where(["id"=>$data["de_id"]])->value("net_id");
        $data['dwdz'] = $this->request->param('dwdz');
        $data['sfjyhx'] = $this->request->param('sfjyhx');
        $data['hdms'] = $this->request->param('hdms');
        $data['hdzp'] = $this->request->param('hdzp');
        $data['dwrq']=date("Y-m-d");
        $data["dwsj"]=date("H:i:s");
        $uid=$this->request->param('userid');
        $data['hbr'] =$this->geteid($uid) ;
      
        $bool = db('yd_schdbf')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    public function qdhblx(){
        $dg=db("yd_qdhblx")->select();
        echo json_encode($dg);
    }

    /**
     * 签到汇报
     */
    public function qdhb(){
        $uid=$this->request->param('userid');
        $id=$this->geteid($uid);
        $where = [];
        if($id){
            $where['qdr'] = $id;
        }

      //  $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('yd_qdhb')->where($where)->order("id desc")->select();
        foreach ($dg as $k => $v) {
            # code...
            $dg[$k]["qdlxtxt"]=db("yd_qdhblx")->where(["id"=>$v["qdlx"]])->value("title");
        }
        echo json_encode($dg);
    }
    /*签到汇报签到*/
    public function addqdhb(){
        $data['qdzp'] = $this->request->param('qdzp');
        $uid=$this->request->param('userid');
        $data['qdlx'] = $this->request->param('qdlx');
        $data['qdms'] = $this->request->param('qdms');
        $data['qddz'] = $this->request->param('qddz');
        $eid=$this->geteid($uid);
        $data['qdr'] =$eid ;
        $data["qdr_name"]=db("employee")->where(["id"=>$eid])->value("em_name");
        $data["qdbm"]=db("department_employee de")->join("department d","de.department_id=d.id")->where(["de.index"=>1,"de.employee_id"=>$eid])->value("d.de_name");
                
        $data["qdrq"]=date("Y-m-d");
        $data["qdsj"]=date("Y-m-d H:i:s");
        $data["dwsj"]=date("Y-m-d H:i:s");
        $data["hbzt"]=1;
         $bool = db('yd_qdhb')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    /**
     * 下属签到汇报
     */
    public function xsqdhb(){
        $uid=$this->request->param('userid');
        $id=$this->geteid($uid);
        $where = [];
        if($id){
            $where['qdr'] = $id;
        }

        $dg = db('yd_qdhb')->where($where)->order("id desc")->select();
        foreach ($dg as $k => $v) {
            # code...
            $dg[$k]["qdlxtxt"]=db("yd_qdhblx")->where(["id"=>$v["qdlx"]])->value("title");
        }
        echo json_encode($dg);
    }

    /**
     * 签到汇报详情
     */
    public function qdhbxq(){
        $id = $this->request->param('id');
        $dg = db('yd_qdhb')->where(['id'=>$id])->find();
        echo json_encode($dg);
    }

    /**
     * 请假申请列表
     */
    public function qjsq(){
        $uid = $this->request->param('userid');
        $eid=$this->geteid($uid);
        $where = "qjr=$eid";
        
        //$page = $this->request->param('page')?$this->request->param('page'):1;
        $dgs = db('yd_qjsq')->where($where)->order("ctime desc")->select();
        $dg=[];
        foreach ($dgs as $k => $v) {
            # code...
            $dg[$k]["id"]=$v["id"];
            $dg[$k]["title"]=$v["title"];
            $dg[$k]["type"]=db("yd_qjlx")->where(["id"=>$v["type"]])->value("title");
            $dg[$k]["sn"]=$v["sn"];
            $dg[$k]["qjts"]=$v["qjts"];
            $dg[$k]["qjxs"]=$v["qjxs"];
            $dg[$k]["state"]=db("cg_ti_hexiao_status")->where(["id"=>$v["state"]])->value("title");
            $dg[$k]["ctime"]=date("Y-m-d H:i:s",$v["ctime"]);
        }
        echo json_encode(['data'=>$dg]);
    }
    public function qjlx(){
        $data=db("yd_qjlx")->select();
        echo json_encode($data);
    }
    /**
     * 添加请假申请
     */
    public function tjqjsq(){
       // echo 1;exit;
        $uid = $this->request->param('userid');
        $eid=$this->geteid($uid);
        if(!$eid){
            echo json_encode(['success'=>false,'msg'=>'error']);die;
        }
        $data["sqr"]=$eid;
        $data["qjr"]=$eid;
        $data["ctime"]=time();
        $data["state"]=1;
        $data["sn"]=$this->produceqjSN();
        $data["type"]=$this->request->param('type');
        if(!$data["type"]){
            echo json_encode(['success'=>false,'msg'=>'请假类型必须选择']);die;
        }
        $data["title"]=$this->request->param('title');
        if(!$data["title"]){
            echo json_encode(['success'=>false,'msg'=>'请假标题不能为空']);die;
        }
        $data["qjsj_ks"]=$this->request->param('qjsj_ks');
        if(!$data["qjsj_ks"]){
            echo json_encode(['success'=>false,'msg'=>'请假开始时间不能为空']);die;
        }
        $data["qjsj_js"]=$this->request->param('qjsj_js');
        if(!$data["qjsj_js"]){
            echo json_encode(['success'=>false,'msg'=>'请假结束时间不能为空']);die;
        }
        $data["qjts"]=$this->request->param('qjts');
        $data["qjxs"]=$this->request->param('qjxs');
        if(!($data["qjts"]||$data["qjxs"])){
             echo json_encode(['success'=>false,'msg'=>'请假时长不能为空']);die;
        }
            
        $data["qjsy"]=$this->request->param('qjsy');
        $data["zp"]=$this->request->param('zp');
        //print_r($data);exit;
        $bool = db('yd_qjsq')->insertGetId($data);
        
        if(false!==$bool){
            $flowId = db('cg_workflowset')->where(['id'=>27])->value('flow_id');
            $post["accessToken"]=$this->gettoken($uid);
            $post['flowId'] = $flowId;
            //print_r($post);
            $post = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post);
            //print_r($post);exit;
            if($post->flowMsg=='提交成功'){
                $insert = [];
                $insert['rwmcjbh']=$data['title'].'['.$data['sn'].']';
                $insert['yw_id'] = $bool;
                $insert['ywlx'] = 27;
                $insert['status'] = 1;
                $insert['department_id'] = db('department_employee')->where(['index'=>1,'employee_id'=>$eid])->value('department_id');
                $insert['sqr_id'] = $eid;
                $insert['workId'] = $post->workId;
                $insert['trackId'] = $post->flowNode->trackId;
                db('cg_workflow')->insert($insert);
                db("yd_qjsq")->where(["id"=>$bool])->update(["state"=>3]);
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'流程提交失败，已保存为草稿']);
            }
            
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    //生成加班申请编号
    public function produceqjSN(){
        //生成编号
        $max = db('yd_qjsq')->where('sn','like',date('Ymd').'%')->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }
    /**
     * 请假申请详情
     */
    public function qjsqxq(){
        $id = $this->request->param('id');
        $datas = db('yd_qjsq')->where('id',$id)->find();
        $data["id"]=$datas["id"];
        $data["title"]=$datas["title"];
        $data["sn"]=$datas["sn"];
        $data["jqr"]=db("employee")->where(["id"=>$datas["qjr"]])->value("em_name");
        $data["jqr_bm"]=db("department_employee de")->join("department d","de.department_id=d.id")->where("de.employee_id={$datas["qjr"]} and de.`index`=1")->value("d.de_name");
        $data["ctime"]=date("Y-m-d H:i:s",$datas["ctime"]);
        $data["qjsj_ks"]=$datas["qjsj_ks"];
        $data["qjsj_js"]=$datas["qjsj_js"];
        $data["qjts"]=$datas["qjts"];
        $data["qjxs"]=$datas["qjxs"];
        $data["qjsy"]=$datas["qjsy"];
        $data["type"]=db("yd_qjlx")->where(["id"=>$datas["type"]])->value("title");
        $log=$this->getlog(27,$id);
        $data["log"]=$log;
        //print_r($log);exit;
        echo json_encode($data);
    }
     //获取审批信息
    public function getlog($fid,$aid){
        $result=[];
        $getwork=db('cg_workflow')->where(["ywlx"=>$fid,"yw_id"=>$aid])->value("workid");
        if($getwork){
            $result=Db::connect('db_config1')->name('tw_hz_log') 
            ->where(['workid'=>$getwork,"action"=>"submit"])->order("ACTIONTIME")->field("USERNAME,MEMO,COMMENTS,ACTIONTIME")
            ->select();
        }

        //print_r($result);
        return $result;
    }
    /**
     * 出差申请列表
     */
    public function ccsq(){
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        
        //$page = $this->request->param('page')?$this->request->param('page'):1;
        $dgs = db('chuchai_apply')->where(["cuser"=>$eid,"is_deleted"=>0])->order("ctime desc")->select();
        $dg=[];
        foreach ($dgs as $k => $v) {
            # code...
            $dg[$k]["id"]=$v["id"];
            $dg[$k]["sn"]=$v["no"];
            $dg[$k]["title"]=$v["title"];
            $dg[$k]["ctime"]=date("Y-m-d H:i:s",$v["ctime"]);
            $dg[$k]["state"]=db("cg_ti_hexiao_status")->where(["id"=>$v["state"]])->value("title");
        }
        echo json_encode(['data'=>$dg]);
    }
     /*提交出差申请至工作流*/
    public function tijiaochuchai(){
        $id=$this->request->param('id');
        if(!$id){
            echo json_encode(['success'=>false,'msg'=>'未传入申请id',"id"=>0]);die;
        }
        $sn=db("chuchai_apply")->where(["id"=>$id])->value("no");

        if(!$sn){
            echo json_encode(['success'=>false,'msg'=>'申请id不存在',"id"=>0]);die;
        }
        $de=db("chuchai_detail")->where(["aid"=>$id])->count();
        if(!$de){
            echo json_encode(['success'=>false,'msg'=>'申请中至少需要一条明细',"id"=>0]);die;
        }
        $uid = $this->request->param('userid');
        if(!$uid){
            echo json_encode(['success'=>false,'msg'=>'未传入userid',"id"=>0]);die;
        }
        $title= $this->request->param('title');
        if(!$title){
            echo json_encode(['success'=>false,'msg'=>'主题不能为空',"id"=>0]);die;
        }
        $title= $this->request->param('title');
        $traveltype= $this->request->param('traveltype');
        $feiyong= $this->request->param('feiyong');
        if(!$feiyong)
            $feiyong=0;
        $target= $this->request->param('target');
        if(!$target){
            echo json_encode(['success'=>false,'msg'=>'行程目的不能为空',"id"=>0]);die;
        }
        $zp= $this->request->param('zp');
         $eid=$this->geteid($uid);
        $adddata["puser"]=$eid;
        $adddata["ptime"]=time();
        $adddata["traveltype"]=$traveltype;
        $adddata["title"]=$title;
        $adddata["feiyong"]=$feiyong;
        $adddata["target"]=$target;
        $adddata["zp"]=$zp;
        $bool=db("chuchai_apply")->where(["id"=>$id])->update($adddata);
        if($bool){
            $flowId = db('cg_workflowset')->where(['id'=>5])->value('flow_id');
            $post["accessToken"]=$this->gettoken($uid);
            $post['flowId'] = $flowId;
            //print_r($post);
            $post = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post);
            //print_r($post);exit;
            if($post->flowMsg=='提交成功'){
                $insert = [];
                $insert['rwmcjbh']=$adddata["title"].'['.$sn.']';
                $insert['yw_id'] = $id;
                $insert['ywlx'] = 5;
                $insert['status'] = 1;
                $insert['department_id'] = db('department_employee')->where(['index'=>1,'employee_id'=>$eid])->value('department_id');
                $insert['sqr_id'] = $eid;
                $insert['workId'] = $post->workId;
                $insert['trackId'] = $post->flowNode->trackId;
                db('cg_workflow')->insert($insert);
                db("chuchai_apply")->where(["id"=>$id])->update(["state"=>3]);
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'流程提交失败，已保存为草稿']);
            }
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }

    /**
     * 添加出差申请
     */
    public function tjccsq(){
        $uid = $this->request->param('userid');
        if(!$uid){
            echo json_encode(['success'=>false,'msg'=>'未传入userid',"id"=>0]);die;
        }
        $title= $this->request->param('title');
        if(!$title){
            echo json_encode(['success'=>false,'msg'=>'主题不能为空',"id"=>0]);die;
        }
        $title= $this->request->param('title');
        $traveltype= $this->request->param('traveltype');
        $feiyong= $this->request->param('feiyong');
        if(!$feiyong)
            $feiyong=0;
        $target= $this->request->param('target');
        if(!$target){
            echo json_encode(['success'=>false,'msg'=>'行程目的不能为空',"id"=>0]);die;
        }
        $zp= $this->request->param('zp');
        //生成单号
        $timenow=date("Ymd");
        $num=Db::table("chuchai_apply")->where("no like '$timenow%'")->count();
        $num++;
        $strnum=$timenow.sprintf("%05d", $num);
        $adddata["no"]=$strnum;
        $eid=$this->geteid($uid);
        $adddata["cuser"]=$eid;
        $adddata["puser"]=$eid;
        $adddata["ctime"]=time();
        $adddata["ptime"]=time();
        $adddata["state"]=1;
        $adddata["traveltype"]=$traveltype;
        $adddata["title"]=$title;
        $adddata["feiyong"]=$feiyong;
        $adddata["target"]=$target;
        $adddata["zp"]=$zp;

        $bool = db('chuchai_apply')->insertGetId($adddata);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok',"id"=>$bool]);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error',"id"=>0]);
        }
    }
    /*出差类型*/
    public function chuchaileixing(){
        $data=[
            ["id"=>1,"title"=>"周边行程申请(当天往返)"],
            ["id"=>2,"title"=>"出差申请(不能当天往返，需产生住宿)"]
        ];
        //1周边行程申请(当天往返)  2出差申请(不能当天往返，需产生住宿)
        echo json_encode($data);
    }
    /*交通工具*/
    public function jtgj(){
        $data=[
            ["id"=>0,"title"=>"火车"],
            ["id"=>1,"title"=>"轮渡"],
            ["id"=>2,"title"=>"飞机"],
            ["id"=>3,"title"=>"大巴"],
            ["id"=>4,"title"=>"自驾车"],
            ["id"=>5,"title"=>"其他"]
        ];
        echo json_encode($data);
    }
    /*陪同人员列表*/
    public function peitongrenlist(){
        $uid = $this->request->param('userid');
        $eid=$this->geteid($uid);
        $data=db("employee")->where("id<>$eid and is_actived=1 and is_deleted=0")->field("id,em_name")->select();
        echo json_encode($data);
    }
    /**
     * 添加出差申请明细
     */
    public function tjccsqmx(){
        $id = $this->request->param('id');
        if(!$id){
            echo json_encode(['success'=>false,'msg'=>'申请id缺失']);die;
        }
        $data["aid"]=$id;
        $data["start"]=$this->request->param('start');
        $data["end"]=$this->request->param('end');
        $data["ts"]=(strtotime($data["end"])-strtotime($data["start"]))/3600/24+1;
        $data["chufa"]=$this->request->param('chufa');
        $data["mudi"]=$this->request->param('mudi');
        $data["gl"]=$this->request->param('gl');
        $data["qishi"]=$this->request->param("qishi");
        $data["fangshi"]=$this->request->param("fangshi");
        $data["shijian"]=$this->request->param("shijian");
        $data["peitongid"]=$this->request->param("peitongid");
        if($data["peitongid"])
            $data["peitongren"]=db("employee")->where(["id"=>$data["peitongid"]])->value("em_name");
        //print_r($data);exit;
        $bool = db('chuchai_detail')->insertGetId($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok',"did"=>$bool]);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error',"did"=>0]);
        }
    }
    /*删除出差明细*/
    public function delccmx(){
        $id = $this->request->param('did');
        $bool = db('chuchai_detail')->where(["id"=>$id])->delete();
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    /**
     * 出差申请详情
     */
    public function ccsqxq(){
        $id = $this->request->param('id');
        $data = db('chuchai_apply')->where('id',$id)->find();
        $data['bm'] = db('department t')->join('department_employee t2','t.id=t2.department_id')->where('t2.employee_id',$data['cuser'])->value('t.de_name');
        $data['cuser_name'] = db('employee')->where('id',$data['cuser'])->value('em_name');
        $data['zw'] = db('job t')->join('job_employee t2','t.id=t2.job_id')->where('t2.employee_id',$data['cuser'])->value('t.job_name');
        $data['xc'] = db('chuchai_detail')->where('aid',$id)->select();
        foreach ($data['xc'] as $k => $v) {
            # code...
            if($v["fangshi"]==1){
                $data['xc'][$k]["jtgj"]="轮渡";
            }else if($v["fangshi"]==2){
                $data['xc'][$k]["jtgj"]="飞机";
            }else if($v["fangshi"]==3){
                $data['xc'][$k]["jtgj"]="大巴";
            }else if($v["fangshi"]==4){
                $data['xc'][$k]["jtgj"]="其他";
            }else{
                $data['xc'][$k]["jtgj"]="火车";
            }
        }
       
        $log=$this->getlog(5,$id);
        $data["log"]=$log;
        echo json_encode($data);
    }
    /*删除出差申请*/
    public function delccapply(){
        $id = $this->request->param('id');
        $bool = db('chuchai_apply')->where(["id"=>$id])->delete();
        db("chuchai_detail")->where(["aid"=>$id])->delete();

        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    /**
     * 加班申请列表
     */
    public function jbsq(){
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $where = ["sqr"=>$eid];
       
        $dgs = db('jiaban_apply')->where($where)->order("ctime desc")->field("id,jbsy,jbkssj,jbjssj,t,xs,sczp,sn,sqr,ctime,state")->select();
        foreach ($dgs as $k => $v) {
            # code...
            $dg[$k]["id"]=$v["id"];
            $dg[$k]["jbsy"]=$v["jbsy"];
            $dg[$k]["sn"]=$v["sn"];
            $dg[$k]["jbkssj"]=$v["jbkssj"];
            $dg[$k]["jbjssj"]=$v["jbjssj"];
            $dg[$k]["t"]=$v["t"];
            $dg[$k]["xs"]=$v["xs"];
            $dg[$k]["ctime"]=date("Y-m-d H:i:s",$v["ctime"]);
            $dg[$k]["state"]=db("cg_ti_hexiao_status")->where(["id"=>$v["state"]])->value("title");
        }
        echo json_encode(['data'=>$dg]);
    }

    /**
     * 添加加班申请
     */
    public function tjjbsq(){
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        if(!$eid){
            echo json_encode(['success'=>false,'msg'=>'userid未传入']);die;
        }
        $data["sqr"]=$eid;
        $data["ctime"]=time();
        $data["state"]=1;
        $data["jbsy"]=$this->request->param('jbsy');
        if(!$data["jbsy"]){
            echo json_encode(['success'=>false,'msg'=>'加班事由不能为空']);die;
        }
        $data["jbkssj"]=$this->request->param('jbkssj');
        if(!$data["jbkssj"]){
            echo json_encode(['success'=>false,'msg'=>'加班开始时间不能为空']);die;
        }
        $data["jbjssj"]=$this->request->param('jbjssj');
        if(!$data["jbjssj"]){
            echo json_encode(['success'=>false,'msg'=>'加班结束时间不能为空']);die;
        }
        $data["t"]=$this->request->param('t');$data["xs"]=$this->request->param('xs');
        if(!($data["t"]||$data["xs"])){
            echo json_encode(['success'=>false,'msg'=>'实际加班时间不能为空']);die;
        }
        $data["sczp"]=$this->request->param('sczp');
        $data['sn'] = $this->produceSN();
        $bool = db('jiaban_apply')->insertGetId($data);
        if(false!==$bool){
             $flowId = db('cg_workflowset')->where(['id'=>28])->value('flow_id');
            $post["accessToken"]=$this->gettoken($uid);
            $post['flowId'] = $flowId;
            //print_r($post);
            $post = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post);
            //print_r($post);exit;
            if($post->flowMsg=='提交成功'){
                $insert = [];
                $insert['rwmcjbh']=$data["jbsy"].'['.$data['sn'].']';
                $insert['yw_id'] = $bool;
                $insert['ywlx'] = 28;
                $insert['status'] = 1;
                $insert['department_id'] = db('department_employee')->where(['index'=>1,'employee_id'=>$eid])->value('department_id');
                $insert['sqr_id'] = $eid;
                $insert['workId'] = $post->workId;
                $insert['trackId'] = $post->flowNode->trackId;
                db('cg_workflow')->insert($insert);
                db("jiaban_apply")->where(["id"=>$bool])->update(["state"=>3]);
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'流程提交失败，已保存为草稿']);
            }
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }

    /**
     * 加班申请详情
     */
    public function jbsqxq(){
        $id = $this->request->param('id');
        $v = db('jiaban_apply')->where('id',$id)->find();
        $dg["id"]=$v["id"];
        $dg["jbsy"]=$v["jbsy"];
        $dg["sn"]=$v["sn"];
        $dg["jbkssj"]=$v["jbkssj"];
        $dg["jbjssj"]=$v["jbjssj"];
        $dg["t"]=$v["t"];
        $dg["xs"]=$v["xs"];
        $dg["ctime"]=date("Y-m-d H:i:s",$v["ctime"]);
        $dg["state"]=db("cg_ti_hexiao_status")->where(["id"=>$v["state"]])->value("title");
        $log=$this->getlog(28,$id);
        $dg["sqr"]=db("employee")->where(["id"=>$v["sqr"]])->value("em_name");
        $dg["sqr_bm"]=db("department_employee de")->join("department d","de.department_id=d.id")->where(["de.employee_id"=>$v["sqr"]])->value("d.de_name");
        $dg["log"]=$log;
        echo json_encode($dg);
    }

    //生成加班申请编号
    public function produceSN(){
        //生成编号
        $max = db('jiaban_apply')->where('sn','like',date('Ymd').'%')->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }

    /**
     * 销售订单列表
     */
    public function xsdd(){
        $type= $this->request->param('type');
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $where="sqr=$eid and cusType=1 ";
        if($type==2){
            //审批中
            $where.="and status in (2,3,4,5,6) ";
        }else if($type==3){
            //待发货
            $where.="and status=7 and (fhzt is null or fhzt=0) ";
        }else if($type==4){
            //待收货
            $where.="and status=7 and fhzt=1 and (shzt is null or shzt=0) ";
        }
        
        $dgs = db('cg_order')->where($where)->order("sqrq desc")->select();
        $dg=[];
        foreach($dgs as $k=>$v){
            $dg[$k]["oid"]=$v["id"];
            $dg[$k]["jxs_id"]=$v["cusName"];
            $dg[$k]["jxs_sn"]=$v["khbh"];
            $dg[$k]["jxs_title"]=$v["khmc"];
            $dg[$k]["sn"]=$v["sn"];
            $dg[$k]["yszje"]=$v["yszje"];
            $dg[$k]["order_status"]=db("cg_order_status")->where(["id"=>$v["status"]])->value("title");
            $dg[$k]["fh_status"]=$v["fhzt"];
            $dg[$k]["sh_status"]=$v["shzt"];
            $dg[$k]["dhsl"] = db('cg_order_list')->where('order_id',$v['id'])->sum('num');
            $dg[$k]["sqrq"]=date("Y-m-d",$v["sqrq"]);
        }
        echo json_encode($dg);
    }

    /**
     * 添加销售订单
     */
    public function tjxsdd(){
        $uid=$this->request->param('userid');
        $jxs_id=$this->request->param('jxs_id');
        $sczp=$this->request->param('sczp');
        $jyfhrq=$this->request->param('jyfhrq');
        $zysx=$this->request->param('zysx');
        $eid=$this->geteid($uid);
        $data['sqr'] = $eid;
        $data["sqrmc"]=db("employee")->where(["id"=>$eid])->value("em_name");
        $data["sqrq"]=time();
        $data["ctime"]=time();
        $data["cuser"]=$eid;
        $data["sn"]=$this->produceodSN();
        $data["yszje"]=0;
        $data["fpType"]=1;
        $data["type_id"]=1;
        $data['sn'] = $this->produceSN();
        $data['cusType']=1;
        $jxs=db("cg_jxs")->where(["id"=>$jxs_id])->find();
        $data["cusName"]=$jxs["id"];
        $data["khbh"]=$jxs["sn"];
        $data["khmc"]=$jxs["title"];
        $data["shdz"]=$jxs["lgs_rcv_addr"];
        $data["shr"]=$jxs["lgs_rcv_one"];
        $data["dh"]=$jxs["lgs_rcv_phone"];
        $data["jyfhrq"]=$jyfhrq;
        $data["status"]=1;
        $data["zysx"]=$zysx;
        $data["zoning"]=db("cg_market_zoning")->where(["id"=>$jxs["zoning"]])->value("title");
        $data["provice"]=db("cg_market_provice")->where(["id"=>$jxs["provice"]])->value("title");
        $data["city"]=db("cg_market_city")->where(["id"=>$jxs["city"]])->value("title");
        $bool = db('cg_order')->insertGetId($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok',"oid"=>$bool]);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error','oid'=>0]);
        }
    }
    /*销售订单选择商品*/
    public function xsddxzsp(){
        $custype=$this->request->param('custype');
        $cusId=$this->request->param('cusid');
        $type=$this->request->param('type');
        if(!$type)
            $type=1;
        if(!($custype&&$cusId)){
           echo json_encode(['success'=>false,'msg'=>'custype,cusid必须传入']);die;
        }else{
            if($custype==1){
                $jid=$cusId;
            }else if($custype==2){
                $jid=db("cg_net n")->join("cg_system s","n.system_id=s.id")->join("cg_jxs j","s.jxs_id=j.id")->where("n.id=$cusId")->value("j.id");
            }else{
                echo json_encode(['success'=>false,'msg'=>'custype值错误']);die;
            }
        }
        if($type==1){
            $prolist=db("pro_products")->where("is_deleted=0 and is_actived=1")->field("id,pro_no,pro_name,format,unit,remark")->select();
        }else{
            $buyed=db("cg_order o")->join("cg_order_list od","od.order_id=o.id")->where("cusType=$custype and cusName='{$cusId}' and status=7 and od.kind=1")
            ->group("product")->column("product");
            //echo json_encode($buyed);die;
            if($buyed){
                $str=implode(',',$buyed);
                $prolist=db("pro_products")->where("is_deleted=0 and is_actived=1 and id in ($str)")->field("id,pro_no,pro_name,format,unit,remark")->select();
            }else{
                $prolist=[];
            }
        }
       
        
        if($jid){
            $groupid=db("price_group_jxs")->where("jid=$jid")->value("gid");
        }else{
            $groupid="";
        }
        
        $today=date("Y-m-d");
        foreach ($prolist as $k => $v) {
            # code...
            $hasprice=0;
            if($groupid){
                $hasprice=db("price_group_product")->where("gid=$groupid and pid={$v["id"]} and start_time<='{$today}' and end_time>='{$today}'")->value("lingshou_price");
            }
            if($hasprice){
                $prolist[$k]["price"]=$hasprice;
            }else{
                $prolist[$k]["price"]=db("pro_price")->where("pid={$v["id"]}")->value("factory");
            }
        }
        echo json_encode($prolist);
    }
    public function neworderadd(){
        //$po=[["product"=>1,"xgj"=>20,"num"=>20],["product"=>2,"xgj"=>40,"num"=>10]];
       // echo json_encode($po);
        $data["cusType"]=$this->request->param('cusType');
        $data["cusName"]=$this->request->param('cusName');
        $eid=$this->geteid($this->request->param('userid'));
        $data["shr"]=$this->request->param('shr');
        $data["shdz"]=$this->request->param('shdz');
        $data["dh"]=$this->request->param('dh');
        $data["jyfhrq"]=$this->request->param('jyfhrq');
        $data["zysx"]=$this->request->param('zysx');
        $data["sczp"]=$this->request->param('sczp');
        $data["ddsqyje"]=$this->request->param('ddsqyje');
        $data["yszje"]=$this->request->param('yszje');


        $prolist=json_decode($this->request->param('prolist'),true);
        if(!$prolist){
           echo json_encode(['success'=>false,'msg'=>'至少一条产品明细']);die;
        }
        $data['sqr'] = $eid;
        $data["sqrmc"]=db("employee")->where(["id"=>$eid])->value("em_name");
        $data["sqrq"]=time();
        $data["ctime"]=time();
        $data["cuser"]=$eid;
        $data["fpType"]=1;
        $data["type_id"]=1;
        $data['sn'] = $this->produceSN();
        if($data["cusType"]==1){
            $jid=$data["cusName"];
            $jxs=db("cg_jxs")->where(["id"=>$jid])->find();
            $data["khbh"]=$jxs["sn"];
            $data["khmc"]=$jxs["title"];
        }else{
            $jid=db("cg_net n")->join("cg_system s","n.system_id=s.id")->join("cg_jxs j","s.jxs_id=j.id")->where("n.id={$data["cusName"]}")->value("j.id");
            $jxs=db("cg_jxs")->where(["id"=>$jid])->find();
            $net=db("cg_net")->where(["id"=>$data["cusName"]])->find();
            $data["khbh"]=$net["sn"];
            $data["khmc"]=$net["title"];
        }
        $data["status"]=1;
        $data["zoning"]=db("cg_market_zoning")->where(["id"=>$jxs["zoning"]])->value("title");
        $data["provice"]=db("cg_market_provice")->where(["id"=>$jxs["provice"]])->value("title");
        $data["city"]=db("cg_market_city")->where(["id"=>$jxs["city"]])->value("title");
        $bool = db('cg_order')->insertGetId($data);
        for($i=0;$i<count($prolist);$i++){
            $tmpdata=$prolist[$i];
            $tmpdata["kind"]=1;
            $tmpdata["unit"]=db("pro_products")->where(["id"=>$tmpdata["product"]])->value("unit");
            $tmpdata["prod_sn"]=db("pro_products")->where(["id"=>$tmpdata["product"]])->value("pro_no");
            $tmpdata["prod_name"]=db("pro_products")->where(["id"=>$tmpdata["product"]])->value("pro_name");
            $product=db("pro_products")->where(["id"=>$tmpdata["product"]])->find();
            $sku=db("pro_sku")->where(["id"=>$product["sku_id"]])->find();
            $tmpdata["sku"]=$sku["sku_name"];
            $series=db("pro_series")->where(["id"=>$sku["series_id"]])->find();
            $tmpdata["series"]=$series["series_name"];
            $category=db("pro_category")->where(["id"=>$series["category_id"]])->find();
            $tmpdata["category"]=$category["category_name"];
            $brand=db("pro_brands")->where(["id"=>$category["brand_id"]])->find();
            $tmpdata["brand"]=$brand["brand_name"];
            $tmpdata['ygj']=$tmpdata['xgj'];
            $tmpdata["yje"]=$tmpdata["ygj"]*$tmpdata["num"];
            $tmpdata["ysje"]=$tmpdata["xgj"]*$tmpdata["num"];
            $tmpdata["order_id"]=$bool;
            $tmpdata["sn"]=$this->producemxSN($tmpdata["order_id"]);
            $tmpdata["xslx"]=1;
              $tmpdata["xsry"]=$eid;
            $bool1 = db('cg_order_list')->insert( $tmpdata);
        }
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
        //echo $bool;
    }
    /*销售人员*/
    public function sealsman(){
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $em=db("employee")->where(["id"=>$eid])->field("em_name,em_no")->select();
        echo json_encode($em);
    }
    /*添加销售订单经销商信息反馈*/
    public function ddjxslist(){
        $jxs=db("cg_jxs")->where("isdel=0")->field("id,title,sn,lgs_rcv_one as shr,lgs_rcv_addr as shdz,lgs_rcv_phone as shdh")->select();
        echo json_encode($jxs);
    }
     /*添加销售订单网点信息反馈*/
    public function ddnetlist(){
        $jxs=db("cg_net")->where("isdel=0")->field("id,title,sn,lgs_rcv_one as shr,lgs_rcv_addr as shdz,lgs_rcv_phone as shdh")->select();
        echo json_encode($jxs);
    }
    /**
     * 添加销售订单明细
     */
    public function tjxsddmx(){
        $uid=$this->request->param('userid');
        $data["kind"]=$this->request->param('kind');
        $data["product"]=$this->request->param('product');
        $data["num"]=$this->request->param('dhsl');
        if($data["kind"]==1){
            $data["unit"]=db("pro_products")->where(["id"=>$data["product"]])->value("unit");
            $data["prod_sn"]=db("pro_products")->where(["id"=>$data["product"]])->value("pro_no");
            $data["prod_name"]=db("pro_products")->where(["id"=>$data["product"]])->value("pro_name");
            $product=db("pro_products")->where(["id"=>$data["product"]])->find();
            $sku=db("pro_sku")->where(["id"=>$product["sku_id"]])->find();
            $data["sku"]=$sku["sku_name"];
            $series=db("pro_series")->where(["id"=>$sku["series_id"]])->find();
            $data["series"]=$series["series_name"];
            $category=db("pro_category")->where(["id"=>$series["category_id"]])->find();
            $data["category"]=$category["category_name"];
            $brand=db("pro_brands")->where(["id"=>$category["brand_id"]])->find();
            $data["brand"]=$brand["brand_name"];
        }else{
            $data["unit"]=db("pro_materials")->where(["id"=>$data["product"]])->value("unit");
            $data["prod_sn"]=db("pro_materials")->where(["id"=>$data["product"]])->value("material_no");
            $data["prod_name"]=db("pro_materials")->where(["id"=>$data["product"]])->value("material_name");
        }
        $data['ygj']=$this->request->param('ygj');
        $data['xgj']=$this->request->param('xgj');
        $data["yje"]=$data["ygj"]*$data["num"];
        $data["ysje"]=$data["xgj"]*$data["num"];
        $data['dzsl']=$this->request->param('dzsl');
        $data["xsry"]=$this->geteid($uid);
        $data["beizhu"]=$this->request->param('beizhu');
        $data["order_id"]=$this->request->param('oid');
        $data["sn"]=$this->producemxSN($data["order_id"]);
        $data["xslx"]=1;
        $bool = db('cg_order_list')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    //order_id
    /*删除订单明细*/
    public function xsddmxdel(){
        $did=$this->request->param('did');
        $bool = db('cg_order_list')->where(["id"=>$did])->delete();
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    /*删除订单*/
    public function xsddsc(){
        $oid=$this->request->param('oid');
        $bool=db("cg_order")->where(["id"=>$oid])->delete();
        db("cg_order_list")->where(["order_id"=>$oid])->delete();
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    /*销售订单产品销售物料列表*/
    public function orderprodetail(){
        $type= $this->request->param('type');
        $title=$this->request->param('title');
        $jxs_id=$this->request->param('jxs_id');
                 //查询产品订购设置
        $dgsz = db('system_param')->where(['t'=>0,'k'=>'dingDanListType'])->value('v');
        //根据经销商查询分组
        $group_id = db('price_group_jxs')->where('jid',$jxs_id)->column('gid');
        if($type==2){
            //销售物料
            $where="m_type=2 and is_actived=1 and is_deleted=0 ";
            if($title)
                $where.="and material_name like '%{$title}%'";
            $pro=db("pro_materials")->where($where)->field("id,material_name as title,unit,factory as ygj,material_no as sn")->select();
        }else{
            //成品
            $where="is_actived=1 and is_deleted=0";
            if($title)
                $where.="and pro_name like '{$title}'";
            $pro=db("pro_products")->where($where)->field("id,pro_name as title,unit,pro_no as sn")->select();
            foreach ($pro as $k => $v) {
                # code...
                $price = db('price_group_product')
                    ->where([
                        'gid'=>['in',$group_id],
                        'pid'=>$v['id'],
                        'start_time'=>['<=',date('Y-m-d')],
                        'end_time'=>['>=',date('Y-m-d')]
                    ])
                    ->field('lingshou_price,fayun_price')->find();
                if($price)
                    $pro[$k]["ygj"]=$price;
                else
                    $pro[$k]["ygj"]=db("pro_price")->where(["pid"=>$v["id"]])->value("factory");
            }
        }
        echo json_encode($pro);
    }

    /**
     * 销售订单详情
     */
    public function xsddxq(){
        $id = $this->request->param('id');
        $data = db('cg_order')->where('id',$id)->field("id,khmc,sqrmc,sqr,sn,fpType,yhPolicymc,sqrq")->find();
        $data["sqrq"]=date("Y-m-d",$data["sqrq"]);
        if($data["fpType"]==1)
            $data["fpType"]="普通发票";
        else
            $data["fpType"]="增值税发票";
        $data['bm'] = db('department t')->join('department_employee t2','t2.department_id=t.id')->where(["t2.employee_id"=>$data["sqr"]])->value('t.de_name');
        $data['zw'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where(["t2.employee_id"=>$data["sqr"]])->value('t.job_name');
        $log=$this->getlog(23,$id);
        $data["log"]=$log;
        $detail= db('cg_order_list')->where('order_id',$id)->field("id as did,xslx,num as dhsl,dzsl,ysje,prod_name")->select();
        foreach ($detail as $k => $v) {
            # code...
            if($v["xslx"]==1){
                $detail[$k]["xslx"]="销售";
            }else if($v["xslx"]==2){
                $detail[$k]["xslx"]="搭赠";
            }else if($v["xslx"]==3){
                $detail[$k]["xslx"]="货补";
            }else{
                $detail[$k]["xslx"]="费补";
            }
        }
        $data["detail"]=$detail;
        echo json_encode($data);
    }

    /**
     * 网点订单列表
     */
    public function wddd(){
        $uid = $this->request->param('userid');
        $eid=$this->geteid($uid);
        $where = ["sqr"=>$eid,"cusType"=>2];
       
        $dg = db('cg_order')->where($where)->order("ctime desc")->field("id as oid,status,sn,khmc,sqrq,yszje")->select();
        foreach ($dg as $k => $v) {
            $dg[$k]["sqrq"]=date("Y-m-d",$v["sqrq"]);
            # code...
            if($v["status"]==1){
                $dg[$k]["status"]="未处理";
            }else if($v["status"]>7){
                $dg[$k]["status"]="已作废";
            }else if($v["status"]<7){
                $dg[$k]["status"]="流程中";
            }else{
                $dg[$k]["status"]="已通过";
            }
        }
        echo json_encode($dg);
    }
    /*网点订单产品销售物料列表*/
    public function netorderprodetail(){
        $type= $this->request->param('type');
        $title=$this->request->param('title');
        $net_id=$this->request->param('net_id');
        $net=db("cg_net")->where(["id"=>$net_id])->find();
        $sys=db("cg_system")->where(["id"=>$net["system_id"]])->find();
        $jxs_id=$sys["jxs"];
                 //查询产品订购设置
        $dgsz = db('system_param')->where(['t'=>0,'k'=>'dingDanListType'])->value('v');
        //根据经销商查询分组
        $group_id = db('price_group_jxs')->where('jid',$jxs_id)->column('gid');
        if($type==2){
            //销售物料
            $where="m_type=2 and is_actived=1 and is_deleted=0 ";
            if($title)
                $where.="and material_name like '%{$title}%'";
            $pro=db("pro_materials")->where($where)->field("id,material_name as title,unit,factory as ygj,material_no as sn")->select();
        }else{
            //成品
            $where="is_actived=1 and is_deleted=0";
            if($title)
                $where.="and pro_name like '{$title}'";
            $pro=db("pro_products")->where($where)->field("id,pro_name as title,unit,pro_no as sn")->select();
            foreach ($pro as $k => $v) {
                # code...
                $price = db('price_group_product')
                    ->where([
                        'gid'=>['in',$group_id],
                        'pid'=>$v['id'],
                        'start_time'=>['<=',date('Y-m-d')],
                        'end_time'=>['>=',date('Y-m-d')]
                    ])
                    ->field('lingshou_price,fayun_price')->find();
                if($price)
                    $pro[$k]["ygj"]=$price;
                else
                    $pro[$k]["ygj"]=db("pro_price")->where(["pid"=>$v["id"]])->value("factory");
            }
        }
        echo json_encode($pro);
    }
    /**
     * 添加网点订单
     */
    public function tjwddd(){
        $uid=$this->request->param('userid');
        $net_id=$this->request->param('net_id');
        $net=db("cg_net")->where(["id"=>$net_id])->find();
        $sys=db("cg_system")->where(["id"=>$net["system_id"]])->find();
        $jxs_id=$sys["jxs"];
        //echo $jxs_id;exit;
        $sczp=$this->request->param('sczp');
        $jyfhrq=$this->request->param('jyfhrq');
        $zysx=$this->request->param('zysx');
        $eid=$this->geteid($uid);
        $data['sqr'] = $eid;
        $data["sqrmc"]=db("employee")->where(["id"=>$eid])->value("em_name");
        $data["sqrq"]=time();
        $data["ctime"]=time();
        $data["cuser"]=$eid;
        $data["sn"]=$this->produceodSN();
        $data["yszje"]=0;
        $data["fpType"]=1;
        $data["type_id"]=1;
        $data['sn'] = $this->produceSN();
        $data['cusType']=2;
        $jxs=db("cg_jxs")->where(["id"=>$jxs_id])->find();
        $data["cusName"]=$net["id"];
        $data["khbh"]=$net["sn"];
        $data["khmc"]=$net["title"];
        $data["shdz"]=$net["lgs_rcv_addr"];
        $data["shr"]=$net["lgs_rcv_one"];
        $data["dh"]=$net["lgs_rcv_phone"];
        $data["jyfhrq"]=$jyfhrq;
        $data["status"]=1;
        $data["zysx"]=$zysx;
        $data["zoning"]=db("cg_market_zoning")->where(["id"=>$jxs["zoning"]])->value("title");
        $data["provice"]=db("cg_market_provice")->where(["id"=>$jxs["provice"]])->value("title");
        $data["city"]=db("cg_market_city")->where(["id"=>$jxs["city"]])->value("title");
        $bool = db('cg_order')->insertGetId($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok',"oid"=>$bool]);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error','oid'=>0]);
        }
    }

    /**
     * 添加网点订单明细
     */
    public function tjwdddmx(){
        $uid=$this->request->param('userid');
        $data["kind"]=$this->request->param('kind');
        $data["product"]=$this->request->param('product');
        $data["num"]=$this->request->param('dhsl');
        if($data["kind"]==1){
            $data["unit"]=db("pro_products")->where(["id"=>$data["product"]])->value("unit");
            $data["prod_sn"]=db("pro_products")->where(["id"=>$data["product"]])->value("pro_no");
            $data["prod_name"]=db("pro_products")->where(["id"=>$data["product"]])->value("pro_name");
            $product=db("pro_products")->where(["id"=>$data["product"]])->find();
            $sku=db("pro_sku")->where(["id"=>$product["sku_id"]])->find();
            $data["sku"]=$sku["sku_name"];
            $series=db("pro_series")->where(["id"=>$sku["series_id"]])->find();
            $data["series"]=$series["series_name"];
            $category=db("pro_category")->where(["id"=>$series["category_id"]])->find();
            $data["category"]=$category["category_name"];
            $brand=db("pro_brands")->where(["id"=>$category["brand_id"]])->find();
            $data["brand"]=$brand["brand_name"];
        }else{
            $data["unit"]=db("pro_materials")->where(["id"=>$data["product"]])->value("unit");
            $data["prod_sn"]=db("pro_materials")->where(["id"=>$data["product"]])->value("material_no");
            $data["prod_name"]=db("pro_materials")->where(["id"=>$data["product"]])->value("material_name");
        }
        $data['ygj']=$this->request->param('ygj');
        $data['xgj']=$this->request->param('xgj');
        $data["yje"]=$data["ygj"]*$data["num"];
        $data["ysje"]=$data["xgj"]*$data["num"];
        $data['dzsl']=$this->request->param('dzsl');
        $data["xsry"]=$this->geteid($uid);
        $data["beizhu"]=$this->request->param('beizhu');
        $data["order_id"]=$this->request->param('oid');
        $data["sn"]=$this->producemxSN($data["order_id"]);
        $data["xslx"]=1;
        $bool = db('cg_order_list')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }

    /**
     * 网点订单详情
     */
    public function wdddxq(){
        $id = $this->request->param('id');
        $data = db('yd_wddd')->where('id',$id)->find();
        $data['detail'] = db('yd_wddd_list')->where('dd_id',$id)->select();
        echo json_encode($data);
    }

    /**
     * 万用申请单列表
     */
    public function wysqd(){
        $uid = $this->request->param('userid');
        $eid=$this->geteid($uid);
        $where = ["cuser"=>$eid,"is_deleted"=>0];
        //$page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('wanneng_apply')->where($where)->order("ctime desc")->field("id,no,title,type,neirong,ctime,state,sczp,iscost")->select();
        foreach ($dg as $k => $v) {
            # code...
            $dg[$k]["type"]=db("wanneng_type")->where("id={$v["type"]}")->value("title");
            $dg[$k]["ctime"]=date("Y-m-d H:i:s",$v["ctime"]);
            $dg[$k]["statetype"]=db("cg_ti_hexiao_status")->where("id={$v["state"]}")->value("title");
        }
        echo json_encode($dg);
    }
    /*万用申请类型*/
    public function wylx(){
        $arr=db("wanneng_type")->select();
        echo json_encode($arr);
    }
    /*部门列表*/
    public function bmlist(){
        $title = $this->request->param('title');
        $where="is_actived=1 and is_deleted=0";
        if($title)
            $where.=" and de_name like '%$title%' ";
        $arr=db("department")->where($where)->field("id,de_name as title")->select();
        echo json_encode($arr);
    }
    /*考核期列表*/
    public function kaohelist(){
        $arr=db("cg_kaoheqi2 k2")->join("cg_kaoheqi1 k1","k2.pid=k1.id")->join("cg_cainian c","k1.cid=c.id")->order("k2.starttime desc")->field("k2.id,k2.title,c.title cainian")->select();
        $data=[];
        foreach ($arr as $k => $v) {
            # code...
            $data[$k]["id"]=$v["id"];
            $data[$k]["title"]=$v["cainian"].'-'.$v["title"];
        }
        echo json_encode($data);
    }
    /*支付方式列表*/
    public function paylist(){
        $arr=db("cg_paymethod")->field("id,title")->select();
        echo json_encode($arr);
    }
    /*人员列表带查询*/
    public function emlist(){
        $title = $this->request->param('title');
        $where="is_actived=1 and is_deleted=0";
        if($title)
            $where.=" and em_name like '%$title%' ";
        $arr=db("employee")->where($where)->field("id,em_name as title")->select();
        echo json_encode($arr);
    }
    /*完整添加万用申请但*/
    public function fullwysqd(){
       
        $mails=$this->request->param();
        $detail=[];
        if(isset($mails["detail"])){
            if($mails["detail"]){
                $detail=$mails["detail"];
            }
        }
        
        
        
        $data['title'] = $this->request->param('title');
        $data['type'] = $this->request->param('type');
        $data['neirong'] = $this->request->param('neirong');
        $data['iscost'] = $this->request->param('iscost');
        $data['sczp'] = $this->request->param('sczp');
        if(!$data["sczp"]){
            $data['sczp'] = $this->request->param('fujian');
        }
        $data['sczp'] = $this->request->param('sczp');
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $data["cuser"]=$eid;
        $data["ctime"]=time();
         //生成单号
                $timenow=date("Ymd");
                $num=Db::table("wanneng_apply")->where("no like '$timenow%'")->count();
                $num++;
                $strnum=$timenow.sprintf("%05d", $num);
                $data["no"]=$strnum;
        $data['bm'] = $this->request->param('bm');
        $data['kaohe'] = $this->request->param('kaohe');
        $data['zhifu'] = $this->request->param('zhifu');
        $data['shoukuan'] = $this->request->param('shoukuan');
        $data["state"]=1;

        $datadetail=[];
        foreach ($detail as $k => $v) {
            # code...
            if($v["feetype"]&&$v["fee"]){
                $datadetail[$k]=$v;

            }
        }
        if($data['iscost']){
            if(!$datadetail){
                echo json_encode(['success'=>false,'msg'=>'请至少添加一条明细','aid'=>0]);die;
            }
        }
        
        Db::startTrans();
        $bool = db('wanneng_apply')->insertGetId($data);
        if($data["iscost"]){
            foreach ($datadetail as $k => $v) {
                # code...
                $datadetail[$k]["aid"]=$bool;
            }
            $bool2=db("wanneng_detail")->insertAll($datadetail);
        }else{
            $bool2=1;
        }
        
        if($bool&&$bool2){
            Db::commit();
            $flowId = db('cg_workflowset')->where(['id'=>6])->value('flow_id');
            $post["accessToken"]=$this->gettoken($uid);
            $post['flowId'] = $flowId;
                    //print_r($post);
            $post = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post);
                    //print_r($post);exit;
                    if($post->flowMsg=='提交成功'){
                        $insert = [];
                        $insert['rwmcjbh']=$data["title"].'['.$data['no'].']';
                        $insert['yw_id'] = $bool;
                        $insert['ywlx'] = 6;
                        $insert['status'] = 1;
                        $insert['department_id'] = db('department_employee')->where(['index'=>1,'employee_id'=>$eid])->value('department_id');
                        $insert['sqr_id'] = $eid;
                        $insert['workId'] = $post->workId;
                        $insert['trackId'] = $post->flowNode->trackId;
                        db('cg_workflow')->insert($insert);
                        db("wanneng_apply")->where(["id"=>$bool])->update(["state"=>3]);
                        echo json_encode(['success'=>true,'msg'=>'ok','aid'=>$bool]);
                    }else{
                        db("wanneng_apply")->where(["id"=>$bool])->delete();
                        db("wanneng_detail")->where(["aid"=>$bool])->delete();
                        echo json_encode(['success'=>false,'msg'=>'工作流提交失败','aid'=>0]);
                    }
            
        }else{
            Db::rollBack();
            echo json_encode(['success'=>false,'msg'=>'error','aid'=>0]);
        }

    }
    /**
     * 添加万用订单
     */
    public function tjwysqd(){
        $data['title'] = $this->request->param('title');
        $data['type'] = $this->request->param('type');
        $data['neirong'] = $this->request->param('neirong');
        $data['iscost'] = $this->request->param('iscost');
        $data['sczp'] = $this->request->param('sczp');
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $data["cuser"]=$eid;
        $data["ctime"]=time();
         //生成单号
                $timenow=date("Ymd");
                $num=Db::table("wanneng_apply")->where("no like '$timenow%'")->count();
                $num++;
                $strnum=$timenow.sprintf("%05d", $num);
                $data["no"]=$strnum;
        $data['bm'] = $this->request->param('bm');
        $data['kaohe'] = $this->request->param('kaohe');
        $data['zhifu'] = $this->request->param('zhifu');
        $data['shoukuan'] = $this->request->param('shoukuan');
        $data["state"]=1;
        $bool = db('wanneng_apply')->insertGetId($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok','aid'=>$bool]);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error','aid'=>0]);
        }
    }
    /*万用申请提交工作流*/
    public function wysqdinflow(){
        $id = $this->request->param('id');
        $data['title'] = $this->request->param('title');
        $data['type'] = $this->request->param('type');
        $data['neirong'] = $this->request->param('neirong');
        $data['iscost'] = $this->request->param('iscost');
        $data['sczp'] = $this->request->param('sczp');
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $data["puser"]=$eid;
        $data["ptime"]=time();
        $data['bm'] = $this->request->param('bm');
        $data['kaohe'] = $this->request->param('kaohe');
        $data['zhifu'] = $this->request->param('zhifu');
        $data['shoukuan'] = $this->request->param('shoukuan');
        $wan=db("wanneng_apply")->where(["id"=>$id])->find();
        if($wan){
            if($wan["state"]==1){
                if($data["iscost"]==1){
                    $det= db("wanneng_detail")->where(["aid"=>$id])->count();
                    if(!$det){
                        echo json_encode(['success'=>false,'msg'=>'包含费用至少添加一条费用明细']);die;
                    }
                }else{
                    db("wanneng_detail")->where(["aid"=>$id])->delete();
                }
                $bool=db("wanneng_apply")->where(["id"=>$id])->update($data);
                if($bool){
                    $flowId = db('cg_workflowset')->where(['id'=>6])->value('flow_id');
                    $post["accessToken"]=$this->gettoken($uid);
                    $post['flowId'] = $flowId;
                    //print_r($post);
                    $post = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post);
                    //print_r($post);exit;
                    if($post->flowMsg=='提交成功'){
                        $insert = [];
                        $insert['rwmcjbh']=$data["title"].'['.$wan['no'].']';
                        $insert['yw_id'] = $id;
                        $insert['ywlx'] = 6;
                        $insert['status'] = 1;
                        $insert['department_id'] = db('department_employee')->where(['index'=>1,'employee_id'=>$eid])->value('department_id');
                        $insert['sqr_id'] = $eid;
                        $insert['workId'] = $post->workId;
                        $insert['trackId'] = $post->flowNode->trackId;
                        db('cg_workflow')->insert($insert);
                        db("wanneng_apply")->where(["id"=>$id])->update(["state"=>3]);
                        echo json_encode(['success'=>true,'msg'=>'ok']);
                    }else{
                        echo json_encode(['success'=>false,'msg'=>'error']);
                    }
                }else{
                     echo json_encode(['success'=>false,'msg'=>'error']);
                }    
            }else{
                echo json_encode(['success'=>false,'msg'=>'此申请已经提交工作流不能反复操作']);
            }
        }else{
            echo json_encode(['success'=>false,'msg'=>'id不存在']);
        }
    }
    /*日常费用科目*/
    public function richangkemuliset(){
        $where="esuseway like '%\"4\"%'";
        $data=db("cg_feiyongkemu3")->where($where)->field("id,title")->select();
        echo json_encode($data);
    }
    /*万用申请明细添加*/
    public function tjwysqmx(){
        $data['aid'] = $this->request->param('aid');
        $data['feetype'] = $this->request->param('feetype');
        $data['fee'] = $this->request->param('fee');
        $data['remark'] = $this->request->param('remark');
        $bool = db('wanneng_detail')->insertGetId($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok','did'=>$bool]);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error','did'=>0]);
        }
    }
    /**
     * 万用申请单详情
     */
    public function wysqdxq(){
        $id = $this->request->param('id');
        $datas = db('wanneng_apply')->where('id',$id)->find();
        $data["id"]=$datas["id"];
        $data["no"]=$datas["no"];
        $data["title"]=$datas["title"];
        $data["neirong"]=$datas["neirong"];
        $data["iscost"]=$datas["iscost"];
        $data["type"]=$datas["type"];
        $data["typetitle"]=db("wanneng_type")->where(["id"=>$datas["type"]])->value("title");
        $data["state"]=db("cg_ti_hexiao_status")->where(["id"=>$datas["state"]])->value("title");
        $data["cuser"]=db("employee")->where(["id"=>$datas["cuser"]])->value("em_name");
        $data["cuser_bm"]=db("department_employee de")->join("department d","d.id=de.department_id")->where(["de.employee_id"=>$datas["cuser"]])->value("d.de_name");
        $data["bm"]=$datas["bm"];
        $data["bm_title"]=db("department")->where(["id"=>$data["bm"]])->value("de_name");
        $data["kaohe"]=$datas["kaohe"];
        $kaohet=db("cg_kaoheqi2 k2")->join("cg_kaoheqi1 k1","k2.pid=k1.id")->join("cg_cainian c","k1.cid=c.id")->where(["k2.id"=>$datas["kaohe"]])->field("k1.id,k2.title,c.title cainian")->find();
        $data["kaohe_title"]=$kaohet["cainian"].'-'.$kaohet["title"];
        $data["zhifu"]=$datas["zhifu"];
        $data["zhifu_title"]=db("cg_paymethod")->where(["id"=>$datas["zhifu"]])->value("title");
        $data["shoukuan"]=$datas["shoukuan"];
        $data["shoukuan_title"]=db("employee")->where(["id"=>$data["shoukuan"]])->value("em_name");
        $detail=db("wanneng_detail")->where(["aid"=>$id])->field("id as did,feetype,fee,remark")->select();
        foreach ($detail as $k => $v) {
            # code...
            $detail[$k]["feetype_title"]=db("cg_feiyongkemu3")->where(["id"=>$v["feetype"]])->value("title");
        }
        $data["detail"]=$detail;
        $log=$this->getlog(6,$id);
        $data["log"]=$log;
        echo json_encode($data);
    }
    /*万用申请明细删除功能*/
    public function wymxsc(){
        $did = $this->request->param('did');
        $bool=db("wanneng_detail")->where(["id"=>$did])->delete();
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    /*万用申请删除*/
    public function wysqsc(){
        $id = $this->request->param('id');
        $wan=db("wanneng_apply")->where(["id"=>$id])->find();
        if($wan){
            if($wan["state"]==1){
                $bool=db("wanneng_apply")->where(["id"=>$id])->update(["is_deleted"=>1]);
                db("wanneng_detail")->where(["aid"=>$id])->delete();
                if(false!==$bool){
                    echo json_encode(['success'=>true,'msg'=>'ok']);
                }else{
                    echo json_encode(['success'=>false,'msg'=>'error']);
                }
            }else{
                echo json_encode(['success'=>false,'msg'=>'只能删除状态为草稿的申请']);
            }
        }else{
            echo json_encode(['success'=>false,'msg'=>'id不存在']);
        }
    }
    /**
     * 日常费用报销列表
     */
    public function rcfybx(){
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $where = ["cuser"=>$eid,"is_actived"=>1,"is_deleted"=>0];
        
        $dg = db('rc_baoxiao_apply')->where($where)->order("ctime desc")->field("id,cuser,ctime,title,pizhunjin,no,state")->select();
        foreach ($dg as $k => $v) {
            # code...
            $dg[$k]["cuser"]=db("employee")->where(["id"=>$v["cuser"]])->value("em_name");
            $dg[$k]["ctime"]=date("Y-m-d",$v["ctime"]);
            $dg[$k]["statetype"]=db("cg_ti_hexiao_status")->where(["id"=>$v["state"]])->value("title");
        }
        echo json_encode($dg);
    }
    //日常费用报销提交前预算验证
    public function goworktest($aid){
        //暂行版本超预算可申请，未预算不可申请
        $tr=Db::table("target_format")->where(["type_id"=>4])->find();
        $apply=Db::table("rc_baoxiao_apply")->where(["id"=>$aid])->find();
        $detail=Db::table("rc_baoxiao_detail")->alias("rc")->join("cg_jxs j","rc.jxs=j.id","LEFT")
            ->where("rc.aid=$aid")->order("rc.id")->field("rc.id,rc.feiid,rc.pizhunfeiyong")->select();
        $isyellow=0;
        $isred=0;
        for($i=0;$i<count($detail);$i++){

                if($tr){
                    $erjikaoheqi=$apply["kaohe"];
                    $yijikaoheqi=Db::table("cg_kaoheqi2")->where(["id"=>$erjikaoheqi])->value("pid");
                    $depart=$apply["jrbm"];
                    $sanjifeiyong=$detail[$i]["feiid"];
                    $erjifeiyong=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("pid");
                    $yijifeiyong=Db::table("cg_feiyongkemu2")->where(["id"=>$erjifeiyong])->value("pid");
                    $where="yijikaoheqi=$yijikaoheqi and type=3 ";
                    if($tr["depart_id"]){
                        $where.="and depart={$depart} ";
                    }else{
                        $where.="and depart is null ";
                    }
                    if($tr["kaoheqi"]==18){
                        $where.="and erjikaoheqi=$erjikaoheqi ";
                    }else{
                        $where.="and erjikaoheqi is null ";
                    }
                    if($tr["feiyong_id"]){
                        if($tr["feiyong_id"]==16){
                            $where.="and sanjifeiyong=$sanjifeiyong ";
                        }else if($tr["feiyong_id"]==15){
                            $where.="and erjifeiyong=$erjifeiyong and sanjifeiyong is null ";
                        }else{
                            $where.="and yijifeiyong=$yijifeiyong and erjifeiyong is null and sanjifeiyong is null ";
                        }
                    }else{
                        $where.="and yijifeiyong is null and erjifeiyong is null and sanjifeiyong is null ";
                    }
                    //echo $where;
                    $yusuan=Db::table("yusuan")->where($where)->find();
                    if($yusuan){
                        $detail[$i]["yid"]=$yusuan["id"];
                        $zongyusuan=$yusuan["jine"];
                        $pizhun=Db::table("yusuan_detail")->where(["yid"=>$yusuan["id"],"type"=>2])->sum("jine");
                        if(!$pizhun)
                            $pizhun=0;
                        $inapply=Db::table("yusuan_detail")->where(["yid"=>$yusuan["id"],"type"=>1])->sum("jine");
                        if(!$inapply)
                            $inapply=0;
                        if($zongyusuan>=$pizhun+$inapply){
                            $detail[$i]["ytype"]=1;
                        }else if($zongyusuan<$pizhun){
                            $detail[$i]["ytype"]=3;
                            $isred=1;
                        }else{
                            $detail[$i]["ytype"]=2;
                            $isyellow=1;
                        }
                    }else{
                        return 0;
                    }
                }else{
                    return 0;
                }
                
            }
            $lamp=db("system_param")->where("k='lamp'")->value("v");
            //1red  2yellow  3no
            if($lamp==1){
                if($isred==1){
                    return 1;
                }
            }else if($lamp==2){
                if($isyellow==1){
                    return 2;
                }
            }


            return $detail;
    }
    public function testmodel(){
        $data=$this->request->param();
        print_r($data);exit;
    }
    /*提交日常费用报销进入工作流*/
    public function rcfybxinflow(){
        $id=$this->request->param('id');
        $apply=db("rc_baoxiao_apply")->where(["id"=>$id])->find();
        if(!$apply){
            echo json_encode(["msg"=>"申请单不存在",'success'=>false]);die;
        }
        if($apply["state"]>1){
            echo json_encode(["msg"=>"单据已经提交工作流",'success'=>false]);die;
        }
        $data['title'] = $this->request->param('title');
        $data['kaohe'] = $this->request->param('kaohe');
        $data['jrbm'] = $this->request->param('jrbm');
        $data['payway'] = $this->request->param('payway');
        $data['reason'] = $this->request->param('reason');
        $data['sczp'] = $this->request->param('sczp');
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $data['puser'] = $eid;
        $data['ptime'] = time();
        $pizhun=db('rc_baoxiao_detail')->where(["aid"=>$id])->sum("pizhunfeiyong");
        if(!$pizhun){
            echo json_encode(['success'=>false,'msg'=>'至少包含一条费用明细，且费用不为空']);
        }
        $feis=db('rc_baoxiao_detail')->where(["aid"=>$id])->group("feiid")->field("feiid")->select();
        $feisid=[];
        foreach ($feis as $k => $v) {
            # code...
            $feisid[]=$v["feiid"];
        }
        $feistr=implode(',',$feisid);
        db('rc_baoxiao_apply')->where(["id"=>$id])->update(["pizhunjin"=>$pizhun,"feis"=>$feistr]);
        $yusuanres=$this->goworktest($id);
       // print_r($yusuanres);exit;
        if($yusuanres){
            if($yusuanres==1){
                echo json_encode(["msg"=>"存在红灯预算，无法提交",'success'=>false]);die;
            }else if($yusuanres==2){
                echo json_encode(["msg"=>"存在红灯或黄灯预算，无法提交",'success'=>false]);die;
            }
            //print_r($yusuanres);exit;
            $ysdata=[];
            for($i=0;$i<count($yusuanres);$i++){
                $ysdata[]=["yid"=>$yusuanres[$i]["yid"],"did"=>$yusuanres[$i]["id"],"aid"=>$id,"jine"=>$yusuanres[$i]["pizhunfeiyong"],"type"=>1];
            }
            $res1=Db::table("yusuan_detail")->insertAll($ysdata);
                
           
            if($res1){
                 $flowId = db('cg_workflowset')->where(['id'=>10])->value('flow_id');
                    $post["accessToken"]=$this->gettoken($uid);
                    $post['flowId'] = $flowId;
                    //print_r($post);
                    $post = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post);
                    //print_r($post);exit;
                    if($post->flowMsg=='提交成功'){
                        $insert = [];
                        $insert['rwmcjbh']=$data["title"].'['.$apply['no'].']';
                        $insert['yw_id'] = $id;
                        $insert['ywlx'] = 10;
                        $insert['status'] = 1;
                        $insert['department_id'] = db('department_employee')->where(['index'=>1,'employee_id'=>$eid])->value('department_id');
                        $insert['sqr_id'] = $eid;
                        $insert['workId'] = $post->workId;
                        $insert['trackId'] = $post->flowNode->trackId;
                        db('cg_workflow')->insert($insert);
                        db("rc_baoxiao_apply")->where(["id"=>$id])->update(["state"=>3]);
                        echo json_encode(['success'=>true,'msg'=>'ok']);die;
                    }else{
                        echo json_encode(['success'=>false,'msg'=>'error']);die;
                    }
            }else{
                
                echo json_encode(["msg"=>"系统繁忙请稍后再试",'success'=>false]);die;
            }
        }else{
            echo json_encode(["msg"=>"存在未设定预算的明细，无法提交",'success'=>false]);die;
        }
    }
    /*添加日常费用报销*/
    public function fullrcfybx(){
        $mails=$this->request->param();
        $detail=[];
        if(isset($mails["detail"])){
            if($mails["detail"]){
                $detail=$mails["detail"];
            }
        }
        if(!$detail){
            echo json_encode(["msg"=>"至少添加一条费用明细",'success'=>false,"aid"=>0]);die;
        }
        $data["pizhunjin"]=0;
        foreach ($detail as $k => $v) {
            # code...
            if($v["feiid"]&&$v["feis"]){
                $data["pizhunjin"]+=$v["feis"];
            }else{
                echo json_encode(["msg"=>"明细费用科目及费用金额不能为空",'success'=>false,"aid"=>0]);die;
            }
        }
        $data['title'] = $this->request->param('title');
        $data['kaohe'] = $this->request->param('kaohe');
        $data['jrbm'] = $this->request->param('jrbm');
        $data['payway'] = $this->request->param('payway');
        $data['reason'] = $this->request->param('reason');
        $data['sczp'] = $this->request->param('sczp');
        if(!$data["sczp"])
            $data['sczp'] = $this->request->param('fujian');
        //生成单号
                $timenow=date("Ymd");
                $num=Db::table("rc_baoxiao_apply")->where("no like '$timenow%'")->count();
                $num++;
                $strnum=$timenow.sprintf("%05d", $num);
                $data["no"]=$strnum;
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $data['cuser'] = $eid;
        $data['ctime'] = time();
        $data['puser'] = $eid;
        $data['ptime'] = time();
        $data['baoxiaoren'] = $eid;
        $data["is_actived"]=1;
        $data["is_deleted"]=0;
        $data["state"]=1;
        $bool = db('rc_baoxiao_apply')->insertGetId($data);
        if($bool){
            foreach ($detail as $k => $v) {
                $detail[$k]["aid"]=$bool;
                $detail[$k]["pizhunfeiyong"]=$v["feis"];
            }
            $bool2=db("rc_baoxiao_detail")->insertAll($detail);
            if($bool&&$bool2){
                echo json_encode(['success'=>true,'msg'=>'ok']);die;
                $yusuanres=$this->goworktest($bool);
                if($yusuanres){
                    if($yusuanres==1){
                        db("rc_baoxiao_apply")->where(["id"=>$bool])->delete();
                        db("rc_baoxiao_detail")->where(["aid"=>$bool])->delete();
                        echo json_encode(["msg"=>"存在红灯预算，无法提交",'success'=>false]);

                        die;
                    }else if($yusuanres==2){
                         db("rc_baoxiao_apply")->where(["id"=>$bool])->delete();
                        db("rc_baoxiao_detail")->where(["aid"=>$bool])->delete();
                        echo json_encode(["msg"=>"存在红灯或黄灯预算，无法提交",'success'=>false]);die;
                    }
                    //print_r($yusuanres);exit;
                    $ysdata=[];
                    for($i=0;$i<count($yusuanres);$i++){
                        $ysdata[]=["yid"=>$yusuanres[$i]["yid"],"did"=>$yusuanres[$i]["id"],"aid"=>$id,"jine"=>$yusuanres[$i]["pizhunfeiyong"],"type"=>1];
                    }
                    $res1=Db::table("yusuan_detail")->insertAll($ysdata);
                        
                   
                    if($res1){
                         $flowId = db('cg_workflowset')->where(['id'=>10])->value('flow_id');
                            $post["accessToken"]=$this->gettoken($uid);
                            $post['flowId'] = $flowId;
                            //print_r($post);
                            $post = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post);
                            //print_r($post);exit;
                            if($post->flowMsg=='提交成功'){
                                $insert = [];
                                $insert['rwmcjbh']=$data["title"].'['.$data['no'].']';
                                $insert['yw_id'] = $bool;
                                $insert['ywlx'] = 10;
                                $insert['status'] = 1;
                                $insert['department_id'] = db('department_employee')->where(['index'=>1,'employee_id'=>$eid])->value('department_id');
                                $insert['sqr_id'] = $eid;
                                $insert['workId'] = $post->workId;
                                $insert['trackId'] = $post->flowNode->trackId;
                                db('cg_workflow')->insert($insert);
                                $feis=db('rc_baoxiao_detail')->where(["aid"=>$bool])->group("feiid")->field("feiid")->select();
                                $feisid=[];
                                foreach ($feis as $k => $v) {
                                    # code...
                                    $feisid[]=$v["feiid"];
                                }
                                $feistr=implode(',',$feisid);
                                db("rc_baoxiao_apply")->where(["id"=>$bool])->update(["state"=>3,"feis"=>$feistr]);
                                echo json_encode(['success'=>true,'msg'=>'ok']);die;
                            }else{
                                 db("rc_baoxiao_apply")->where(["id"=>$bool])->delete();
                                db("rc_baoxiao_detail")->where(["aid"=>$bool])->delete();
                                echo json_encode(['success'=>false,'msg'=>'error']);die;
                            }
                    }else{
                         db("rc_baoxiao_apply")->where(["id"=>$bool])->delete();
                        db("rc_baoxiao_detail")->where(["aid"=>$bool])->delete();
                        echo json_encode(["msg"=>"系统繁忙请稍后再试",'success'=>false]);die;
                    }
                }else{
                     db("rc_baoxiao_apply")->where(["id"=>$bool])->delete();
                    db("rc_baoxiao_detail")->where(["aid"=>$bool])->delete();
                    echo json_encode(["msg"=>"存在未设定预算的明细，无法提交",'success'=>false]);die;
                }
            }else{
                echo json_encode(['success'=>false,'msg'=>'error',"aid"=>0]);
            }
        }else{
             echo json_encode(['success'=>false,'msg'=>'error',"aid"=>0]);
        }
    }
    /**
     * 添加日常费用报销
     */
    public function tjrcfybx(){
        $data['title'] = $this->request->param('title');
        $data['kaohe'] = $this->request->param('kaohe');
        $data['jrbm'] = $this->request->param('jrbm');
        $data['payway'] = $this->request->param('payway');
        $data['reason'] = $this->request->param('reason');
        $data['sczp'] = $this->request->param('sczp');
        //生成单号
                $timenow=date("Ymd");
                $num=Db::table("rc_baoxiao_apply")->where("no like '$timenow%'")->count();
                $num++;
                $strnum=$timenow.sprintf("%05d", $num);
                $data["no"]=$strnum;
        $uid=$this->request->param('userid');
        $eid=$this->geteid($uid);
        $data['cuser'] = $eid;
        $data['ctime'] = time();
        $data['puser'] = $eid;
        $data['ptime'] = time();
        $data['baoxiaoren'] = $eid;
        $data["is_actived"]=1;
        $data["is_deleted"]=0;
        $data["state"]=1;
        $data["pizhunjin"]=0;

        $bool = db('rc_baoxiao_apply')->insertGetId($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok',"aid"=>$bool]);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error',"aid"=>0]);
        }
    }

    /**
     * 添加日常费用报销明细
     */
    public function tjrcfybxmx(){
        $data['feiid'] = $this->request->param('feiid');
        $data['feis'] = $this->request->param('feis');
        $data['aid'] = $this->request->param('aid');
        if(!$data['aid']){
            echo json_encode(['success'=>false,'msg'=>'请传入aid']);die;
        }
        if(!$data['feiid']){
            echo json_encode(['success'=>false,'msg'=>'费用科目不能为空']);die;
        }
        if(!$data["feis"]){
            echo json_encode(['success'=>false,'msg'=>'金额不能为0']);die;
        }
        $baoxiao=db('rc_baoxiao_apply')->where(["id"=>$data["aid"]])->find();
        if(!$baoxiao){
            echo json_encode(['success'=>false,'msg'=>'申请不存在']);die;
        }
        if($baoxiao["state"]>1){
            echo json_encode(['success'=>false,'msg'=>'状态不允许修改']);die;
        }
        $data['start'] = $this->request->param('start');
        $data['end'] = $this->request->param('end');
        $data['chufa'] = $this->request->param('chufa');
        $data['mudi'] = $this->request->param('mudi');
        $data['remark'] = $this->request->param('remark');
        $data['jxs'] = $this->request->param('jxs');
        $data["pizhunfeiyong"]=$data["feis"];
        $bool = db('rc_baoxiao_detail')->insert($data);
        $pizhun=db('rc_baoxiao_detail')->where(["aid"=>$data["aid"]])->sum("pizhunfeiyong");
        $feis=db('rc_baoxiao_detail')->where(["aid"=>$data["aid"]])->group("feiid")->field("feiid")->select();
        $feisid=[];
        foreach ($feis as $k => $v) {
            # code...
            $feisid[]=$v["feiid"];
        }
        $feistr=implode(',',$feisid);
        db('rc_baoxiao_apply')->where(["id"=>$data["aid"]])->update(["pizhunjin"=>$pizhun,"feis"=>$feistr]);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }

    /**
     * 日常费用报销详情
     */
    public function rcfybxxq(){
        $id = $this->request->param('id');
        $data = db('rc_baoxiao_apply')->where('id',$id)->field("id,no,cuser,ctime,title,no,payway,kaohe,baoxiaoren")->find();
        $data["cuser_bm"]=db("department_employee de")->join("department d","de.department_id=d.id")->where(["de.employee_id"=>$data["cuser"]])->value("d.de_name");
        $data["cuser"]=db("employee")->where(["id"=>$data["cuser"]])->value("em_name");

        $data["ctime"]=date("Y-m-d",$data["ctime"]);
        $data["payway_title"]=db("cg_paymethod")->where(["id"=>$data["payway"]])->value("title");
        $kaohet=db("cg_kaoheqi2 k2")->join("cg_kaoheqi1 k1","k2.pid=k1.id")->join("cg_cainian c","k1.cid=c.id")->where(["k2.id"=>$data["kaohe"]])->field("k1.id,k2.title,c.title cainian")->find();
        $data["kaohe_title"]=$kaohet["cainian"].'-'.$kaohet["title"];
        $shiyongren=db("employee")->where(["id"=>$data["baoxiaoren"]])->value("em_name");
        $detail = db('rc_baoxiao_detail')->where('aid',$id)->field("id as did,feiid,feis,pizhunfeiyong,remark")->select();
        foreach ($detail as $k => $v) {
            # code...
            $detail[$k]["syr"]=$shiyongren;
            $detail[$k]["feiid_title"]=db("cg_feiyongkemu3")->where(["id"=>$v["feiid"]])->value("title");

        }
        $data["detail"]=$detail;
        $log=$this->getlog(10,$id);
        $data["log"]=$log;
        echo json_encode($data);
    }
    /*删除日常费用报销明细*/
    public function rcfybxmxsc(){
        $did = $this->request->param('did');
        $aid=db("rc_baoxiao_detail")->where(["id"=>$did])->value("aid");
        if($aid){
            $apply=db("rc_baoxiao_apply")->where(["id"=>$aid])->find();
            if($apply){
                if($apply["state"]==1){
                    $bool=db("rc_baoxiao_detail")->where(["id"=>$did])->delete();
                    $pizhun=db('rc_baoxiao_detail')->where(["aid"=>$aid])->sum("pizhunfeiyong");
                    $feis=db('rc_baoxiao_detail')->where(["aid"=>$aid])->group("feiid")->field("feiid")->select();
                    $feisid=[];
                    foreach ($feis as $k => $v) {
                        # code...
                        $feisid[]=$v["feiid"];
                    }
                    $feistr=implode(',',$feisid);
                    db('rc_baoxiao_apply')->where(["id"=>$aid])->update(["pizhunjin"=>$pizhun,"feis"=>$feistr]);
                    if(false!==$bool){
                        echo json_encode(['success'=>true,'msg'=>'ok']);
                    }else{
                        echo json_encode(['success'=>false,'msg'=>'error']);
                    }
                }else{
                    echo json_encode(['success'=>false,'msg'=>'单据状态不允许修改']);
                }
            }else{
                echo json_encode(['success'=>false,'msg'=>'明细id不存在']);
            }
        }else{
            echo json_encode(['success'=>false,'msg'=>'明细id不存在']);
        }
    }
    /*日常费用报销删除*/
    public function rcfybxsc(){
        $aid=$this->request->param('id');
        $apply=db("rc_baoxiao_apply")->where(["id"=>$aid])->find();
        if($apply){
            if($apply["state"]==1){
                $bool=db('rc_baoxiao_apply')->where(["id"=>$aid])->update(["is_actived"=>0]);
                if(false!==$bool){
                        echo json_encode(['success'=>true,'msg'=>'ok']);
                    }else{
                        echo json_encode(['success'=>false,'msg'=>'error']);
                    }
            }else{
                echo json_encode(['success'=>false,'msg'=>'单据状态不允许修改']);
            }
        }else{
            echo json_encode(['success'=>false,'msg'=>'id不存在']);
        }
    }
    /**
     * 退货管理列表
     */
    public function thgl(){
        $where = [];
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('yd_thgl')->where($where)->limit(($page-1)*10,10)->select();
        foreach($dg as $k=>$v){
            $v['thsl'] = db('yd_thgl_detail')->where('order_id',$v['id'])->sum('thsl');
            $v['thje'] = db('yd_thgl_detail')->where('order_id',$v['id'])->sum('thje');
            $dg[$k] = $v;
        }
        echo json_encode($dg);
    }

    /**
     * 添加退货管理
     */
    public function tjth(){
        $data = Request::instance()->post();
        $data['cuser'] = session('employee_id');
        $data['ctime'] = time();
        $bool = db('yd_thgl')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }

    /**
     * 添加退货管理明细
     */
    public function tjthmx(){
        $data = Request::instance()->post();
        $bool = db('yd_thgl_detail')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }

    /**
     * 退货管理详情
     */
    public function thxq(){
        $id = $this->request->param('id');
        $data = db('yd_thgl')->where('id',$id)->find();
        $data['detail'] = db('yd_thgl_detail')->where('order_id',$id)->select();
        echo json_encode($data);
    }

    /**
     * 市场活动申请列表
     */
    public function schdsq(){
        $type_id = $this->request->param('type_id');
        $where = [];
        if($type_id){
            $where['type_id'] = $type_id;
        }
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('cg_ti')->where($where)->limit(($page-1)*10,10)->select();
        foreach ($dg as $k => $v) {
            # code...
            $dg[$k]["ctime"]=date("Y-m-d H:i:s", $dg[$k]["ctime"]);
            $dg[$k]["statename"]=db("cg_ti_hexiao_status")->where("id",$v["status"])->value("title");
        }
        echo json_encode($dg);
    }

    /**
     * 活动执行检查列表
     */
    public function hdzxjclb(){
      
       
        $where="t.status=7 and (td.net_id is not null or td.net_id<>'')";
       
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('cg_ti t')->join("cg_ti_list td","td.ti_id=t.id")->join("cg_net n","td.net_id=n.id")->group("td.net_id")->where($where)->order("net_id")->limit(($page-1)*10,10)->field("n.id as net_id,n.sn,n.title,n.detailAddress,n.lat,n.lng")->select();
        echo json_encode($dg);
    }

    /**
     * 网点活动明细
     */
    public function wdhdmx(){
        $net_id = $this->request->param('net_id');
        $where = [];
        $where["t.status"]=7;
        if($net_id){
            $where['t2.net_id'] = $net_id;
        }
        $net_name = db('cg_net')->where('id',$net_id)->value('title');
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('cg_ti t')->join('cg_ti_list t2','t.id=t2.ti_id')->where($where)->limit(($page-1)*10,10)->field("t2.id,product,sku,series,category,brand,feetype,start,end,t.sn,t2.sn as sn2,t.type_id")->select();
        $dgs=[];
        foreach ($dg as $k => $v) {
            # code...
            $dgs[$k]["id"]=$v["id"];
            $dgs[$k]["sn"]=$v["sn"]."-".$v["sn2"];
            if($v["product"]){
                $dgs[$k]["product_type"]="产品";
                $dgs[$k]["product"]=db("pro_products")->where(["id"=>$v["product"]])->value("pro_name");
            }else if($v["sku"]){
                $dgs[$k]["product_type"]="sku";
                $dgs[$k]["product"]=db("pro_sku")->where(["id"=>$v["sku"]])->value("sku_name");
            }else if($v["series"]){
                $dgs[$k]["product_type"]="系列";
                $dgs[$k]["product"]=db("pro_series")->where(["id"=>$v["series"]])->value("series_name");
            }else if($v["category"]){
                $dgs[$k]["product_type"]="品类";
                $dgs[$k]["product"]=db("pro_category")->where(["id"=>$v["category"]])->value("category_name");
            }else{
                $dgs[$k]["product_type"]="品牌";
                $dgs[$k]["product"]=db("pro_brands")->where(["id"=>$v["brand"]])->value("brand_name");
            }
            $dgs[$k]["start"]=date("Y-m-d",$v["start"]);$dgs[$k]["end"]=date("Y-m-d",$v["end"]);
            $dgs[$k]["feetype"]=db("cg_feiyongkemu3")->where("id",$v["feetype"])->value("title");
            $dgs[$k]["type_id"]=$v["type_id"];

        }
        echo json_encode(['data'=>$dgs,'net_name'=>$net_name]);
    }
    /*新增活动检查*/
    public function newschdjc(){
        $data["de_id"] = $this->request->param('id');
        $data["qddesc"] = $this->request->param('qddesc');
        $data["address"] = $this->request->param('address');
        $data["lat"] = $this->request->param('lat');
        $data["lng"] = $this->request->param('lng');
        $data["cuser"]=$this->request->param('userid');
        $data["cuser"]=$this->geteid($data["cuser"]);
        $data["photo"] = $this->request->param('photo');
        $data["qdtype"] = $this->request->param('qdtype');
        $data["ctime"]=date("Y-m-d H:i:s");
        $data["status"]=0;
        if(!$data["de_id"]){
            echo json_encode(['success'=>false,'msg'=>'id不能为空']);return;
        }
        if(!$data["qddesc"]){
            echo json_encode(['success'=>false,'msg'=>'签到描述不能为空']);return;
        }
        $res=db("yd_schdjc")->insertGetId($data);
        if($res){
            echo json_encode(['success'=>true,'msg'=>'ok']);return;
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);return;
        }
    }
    //活动检查签到类型
    public function newschdjctype(){
        $dgs=db("yd_schdjc_type")->select();
        echo json_encode(['data'=>$dgs]);
    }
    public function schdjctijiao(){
        $ids=$this->request->param('ids');
        $eid=$this->request->param('userid');
        $eid=$this->geteid($eid);
        if(!$ids){
            echo json_encode(['success'=>false,'msg'=>'未选择网点']);return;
        }
        db("yd_schdjc")->where("cuser={$eid} and de_id in ({$ids})")->update(["status"=>1]);
          echo json_encode(['success'=>true,'msg'=>'ok']);return;
    }
    /*活动检查列表*/
    public function schdjclist(){
        $id = $this->request->param('id');
        $v=db('cg_ti t')->join('cg_ti_list t2','t.id=t2.ti_id')->where(["t2.id"=>$id])->field("t2.id,product,sku,series,category,brand,feetype,start,end,t.sn,t2.sn as sn2,t.type_id,t2.net_id,t.type_id")->find();
        $dgs=[];
            //0：非常规，1进场,2常规
            if($v["type_id"]==1){
                $dgs["type"]="进场活动";
            }else if($v["type_id"]==2){
                $dgs["type"]="常规活动";
            }else{
                $dgs["type"]="非常规活动";
            }
            if($v["product"]){
                $dgs["product_type"]="产品";
                $dgs["product"]=db("pro_products")->where(["id"=>$v["product"]])->value("pro_name");
            }else if($v["sku"]){
                $dgs["product_type"]="sku";
                $dgs["product"]=db("pro_sku")->where(["id"=>$v["sku"]])->value("sku_name");
            }else if($v["series"]){
                $dgs["product_type"]="系列";
                $dgs["product"]=db("pro_series")->where(["id"=>$v["series"]])->value("series_name");
            }else if($v["category"]){
                $dgs["product_type"]="品类";
                $dgs["product"]=db("pro_category")->where(["id"=>$v["category"]])->value("category_name");
            }else{
                $dgs["product_type"]="品牌";
                $dgs["product"]=db("pro_brands")->where(["id"=>$v["brand"]])->value("brand_name");
            }
        $dgs['net_name'] = db('cg_net')->where('id',$v["net_id"])->value('title');
        $list=db("yd_schdjc")->where(["de_id"=>$id])->field("id,address,ctime,cuser,status,qddesc")->select();
        foreach ($list as $k => $v) {
            # code...0草稿  1已提交 2已审核
            if($v["status"]==1){
                $list[$k]["status"]="已提交";
            }else if($v["status"]==2){
                $list[$k]["status"]="已审核";
            }else{
                $list[$k]["status"]="草稿";
            }
            $list[$k]["cuser"]=db("employee")->where(["id"=>$v["cuser"]])->value("em_name");
        }
        $dgs["hdlist"]=$list;
        echo json_encode(['data'=>$dgs]);
    }
    /**
     * 活动执行审核网点列表
     */
    public function hdzxsh(){
        $type= $this->request->param('type');
        $where="hd.shzt<>1 or hd.shzt is null";
        if($type==1){
            $where="hd.shzt=1";
        }
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('yd_schdbf hd')->join("cg_ti_list t2","hd.de_id=t2.id")->join("cg_net n","t2.net_id=n.id")->where($where)->group("t2.net_id")->limit(($page-1)*10,10)->field("n.id as net_id,n.sn,n.title,n.detailAddress")->select();
        echo json_encode($dg);
    }

    /**
     * 活动执行审核网点列表明细
     */
    public function hdzxshmx(){
        $net_id = $this->request->param('net_id');
        $type= $this->request->param('type');
        //$where = [];
         $where="(hd.shzt<>1 or hd.shzt is null) and t2.net_id={$net_id} and t.status=7";
        if($type==1){
            $where="hd.shzt=1 and t2.net_id={$net_id} and t.status=7 and t.status2=0";
        }
        $net_name = db('cg_net')->where('id',$net_id)->value('title');
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('yd_schdbf hd')->join("cg_ti_list t2","hd.de_id=t2.id")->join("cg_ti t","t2.ti_id=t.id")->where($where)->field("t2.id,product,sku,series,category,brand,feetype,start,end,t.sn,t2.sn as sn2,t.type_id,t2.net_id,t.type_id")->group("t2.id")->limit(($page-1)*10,10)->select();
        $dgs=[];
        foreach ($dg as $k => $v) {
            # code...
            $dgs[$k]["id"]=$v["id"];
            $dgs[$k]["sn"]=$v["sn"]."-".$v["sn2"];
            if($v["product"]){
                $dgs[$k]["product_type"]="产品";
                $dgs[$k]["product"]=db("pro_products")->where(["id"=>$v["product"]])->value("pro_name");
            }else if($v["sku"]){
                $dgs[$k]["product_type"]="sku";
                $dgs[$k]["product"]=db("pro_sku")->where(["id"=>$v["sku"]])->value("sku_name");
            }else if($v["series"]){
                $dgs[$k]["product_type"]="系列";
                $dgs[$k]["product"]=db("pro_series")->where(["id"=>$v["series"]])->value("series_name");
            }else if($v["category"]){
                $dgs[$k]["product_type"]="品类";
                $dgs[$k]["product"]=db("pro_category")->where(["id"=>$v["category"]])->value("category_name");
            }else{
                $dgs[$k]["product_type"]="品牌";
                $dgs[$k]["product"]=db("pro_brands")->where(["id"=>$v["brand"]])->value("brand_name");
            }
            $dgs[$k]["start"]=date("Y-m-d",$v["start"]);$dgs[$k]["end"]=date("Y-m-d",$v["end"]);
            $dgs[$k]["feetype"]=db("cg_feiyongkemu3")->where("id",$v["feetype"])->value("title");
            ////0：非常规，1进场,2常规
            if($v["type_id"]==0){
                $dgs[$k]["type"]="非常规活动";
            }else if($v["type_id"]==1){
                $dgs[$k]["type"]="进场活动";
            }else{
                $dgs[$k]["type"]="常规活动";
            }
        }
       
        echo json_encode(['data'=>$dgs,'net_name'=>$net_name]);
    }

    /**
     * 活动执行审核网点列表明细汇报列表
     */
    public function hdzxshmxhblb(){
        $id = $this->request->param('id');
        $type= $this->request->param('type');
        $where="(hd.shzt<>1 or hd.shzt is null) and de_id={$id}";
        if($type==1){
            $where="hd.shzt=1 and de_id=$id";
        }
        $ti=db("cg_ti_list")->where(["id"=>$id])->field("net_id,product,sku,series,category,brand,start,end")->find();
        $net_name=db("cg_net")->where("id={$ti["net_id"]}")->value("title");
        $start=date("Y-m-d",$ti["start"]);$end=date("Y-m-d",$ti["end"]);
         if($ti["product"]){
                $product_type="产品";
                $product=db("pro_products")->where(["id"=>$ti["product"]])->value("pro_name");
            }else if($ti["sku"]){
                $product_type="sku";
                $product=db("pro_sku")->where(["id"=>$ti["sku"]])->value("sku_name");
            }else if($ti["series"]){
                $product_type="系列";
                $product=db("pro_series")->where(["id"=>$ti["series"]])->value("series_name");
            }else if($ti["category"]){
                $product_type="品类";
                $product=db("pro_category")->where(["id"=>$ti["category"]])->value("category_name");
            }else{
                 $product_type="品牌";
                 $product=db("pro_brands")->where(["id"=>$v["brand"]])->value("brand_name");
            }
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg=db('yd_schdbf hd')->where($where)->field("id,hbr,dwrq,sfjyhx,hdms,dwsj,shzt")->select();
        foreach ($dg as $k => $v) {
            # code...
            if(!$v["shzt"])
                $dg[$k]["shzt"]="待审核";
            if($v["shzt"]==1)
                $dg[$k]["shzt"]="已审核";
            if($v["shzt"]==2)
                $dg[$k]["shzt"]="重新修改";
            $dg[$k]["hbr"]=db("employee")->where(["id"=>$v["hbr"]])->value("em_name");
           
        }
        echo json_encode(['data'=>$dg,'net_name'=>$net_name,'product'=>$product,'product_type'=>$product_type,'start'=>$start,'end'=>$end]);
    }
    /*
    市场活动审核页面

     */
    public function schdshpage(){
        $id = $this->request->param('id');
        $hd=db('yd_schdbf')->where(["id"=>$id])->find();
        $net_id=db("cg_ti_list")->where("id={$hd["de_id"]}")->value("net_id");
        $net_name=db("cg_net")->where(["id"=>$net_id])->value("title");
        $dg=db("yd_schdbf_dp")->where(["bf_id"=>$id])->select();
        foreach ($dg as $k => $v) {
            # code...
            $dg[$k]["cuser"]=db("employee")->where(["id"=>$v["cuser"]])->value("em_name");
        }
        echo json_encode(['data'=>$dg,'net_name'=>$net_name,'sfjyhx'=>$hd["sfjyhx"],'address'=>$hd["dwdz"],"hdms"=>$hd["hdms"],"hdzp"=>$hd["hdzp"]]);
    }
    /**
     * 市场活动审核通过
     */
    public function schdshtg(){
        $id = $this->request->param('id');
        $dpxx = $this->request->param('dpxx');
        $bool = db('yd_schdbf')->where('id',$id)->update(['shzt'=>1]);
        $data["bf_id"]=$id;
        $data["cuser"]=$this->geteid( $this->request->param('userid'));
        $data["ctime"]=date("Y-m-d H:i:s");
        $data["dpxx"]=$dpxx;
        $data["status"]=1;
        db("yd_schdbf_dp")->insertGetId($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }

    /**
     * 市场活动重新整改
     */
    public function schdcxzg(){
        $id = $this->request->param('id');
         $dpxx = $this->request->param('dpxx');
        $bool = db('yd_schdbf')->where('id',$id)->update(['shzt'=>2]);
         $data["bf_id"]=$id;
        $data["cuser"]=$this->geteid( $this->request->param('userid'));
        $data["ctime"]=date("Y-m-d H:i:s");
        $data["dpxx"]=$dpxx;
        $data["status"]=2;
        db("yd_schdbf_dp")->insertGetId($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }



    /**
     * 活动执行反馈网点列表
     */
    public function schdfk(){
        $fb = $this->request->param('fb');
        $where="fb=0 and status=7  and status2 is null";
        if($fb==1){
             $where="fb=1 and status=7 and status2 is null";
        }
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('cg_ti')->where($where)->order("ctime desc")->field("id,fb,sn,title,jxs_id,ctime,type_id")->limit(($page-1)*10,10)->select();
        foreach ($dg as $k => $v) {
            $dg[$k]["jxs"]=db("cg_jxs")->where(["id"=>$v["jxs_id"]])->value("title");
            # code...
            if($v["type_id"]==0){
                $dg[$k]["type"]="非常规活动";
            }else if($v["type_id"]==1){
                $dg[$k]["type"]="进场活动";
            }else{
                $dg[$k]["type"]="常规活动";
            }
            $dg[$k]["ctime"]=date("Y-m-d",$v["ctime"]);
            if($fb==1)
                $dg[$k]["fb_actualtax"]=db("cg_ti_list")->where("ti_id={$v["id"]}")->sum("yjsjtrfy");
            else
                $dg[$k]["fb_actualtax"]=db("cg_ti_list")->where("ti_id={$v["id"]}")->sum("fb_shijitourufeiyong");
            $dg[$k]["status"]="已归档";
        }
        echo json_encode($dg);
    }

    /**
     * 活动执行反馈网点列表明细
     */
    public function schdfkmx(){
        $id = $this->request->param('id');
        $where = [];
        if($id){
            $where['t2.ti_id'] = $id;
        }
        //$net_name = db('cg_net')->where('id',$net_id)->value('title');
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $title=db("cg_ti")->where("id=$id")->value("title");
        $type=db("cg_ti")->where("id=$id")->value("type_id");
        if($type==1){
            $type="进场活动";
        }else if($type==2){
            $type="常规促销活动";
        }else{
            $type="非常规促销活动";
        }
        $dg = db('cg_ti t')->join('cg_ti_list t2','t.id=t2.ti_id')->where($where)->field("t2.id,t.jxs_id,t2.net_id,product,sku,series,category,brand,t2.start,t2.end,t2.feetype,t2.yjsjtrfy,t2.fb_shijitourufeiyong,t2.totalExpectedSales,fb_shijixiaoliang")->select();
        foreach ($dg as $k => $v) {
            # code...
            $dg[$k]["jxs"]=db("cg_jxs")->where("id={$v["jxs_id"]}")->value("title");
            $dg[$k]["net"]=db("cg_net")->where(["id"=>$v["net_id"]])->value("title");
            if($v["product"]){
                $dg[$k]["product_type"]="产品";
                $dg[$k]["product"]=db("pro_products")->where(["id"=>$v["product"]])->value("pro_name");
            }else if($v["sku"]){
                $dg[$k]["product_type"]="sku";
                $dg[$k]["product"]=db("pro_sku")->where(["id"=>$v["sku"]])->value("sku_name");
            }else if($v["series"]){
                $dg[$k]["product_type"]="系列";
                $dg[$k]["product"]=db("pro_series")->where(["id"=>$v["series"]])->value("series_name");
            }else if($v["category"]){
                $dg[$k]["product_type"]="品类";
                $dg[$k]["product"]=db("pro_category")->where(["id"=>$v["category"]])->value("category_name");
            }else{
                $dg[$k]["product_type"]="品牌";
                $dg[$k]["product"]=db("pro_brands")->where(["id"=>$v["brand"]])->value("brand_name");
            }
            $dg[$k]["start"]=date("Y-m-d",$v["start"]);$dg[$k]["end"]=date("Y-m-d",$v["end"]);
            $dg[$k]["feetype"]=db("cg_feiyongkemu3")->where("id",$v["feetype"])->value("title");
        }
        echo json_encode(['data'=>$dg,'title'=>$title,"type"=>$type]);
    }

    /**
     * 活动执行反馈网点列表明细汇报列表
     */
    public function schdfkmxhblb(){
        $id = $this->request->param('id');
        $hd=db('yd_schdbf')->where(["de_id"=>$id])->find();
        $net_id=db("cg_ti_list")->where("id={$id}")->value("net_id");
        $net_name=db("cg_net")->where(["id"=>$net_id])->value("title");
        $dg=db("yd_schdbf_dp")->where(["bf_id"=>$id])->field("cuser,ctime,dpxx,status")->select();
        foreach ($dg as $k => $v) {
            # code...
            $dg[$k]["cuser"]=db("employee")->where(["id"=>$v["cuser"]])->value("em_name");
        }
        echo json_encode(['data'=>$dg,'net_name'=>$net_name,'sfjyhx'=>$hd["sfjyhx"],'address'=>$hd["dwdz"],"hdms"=>$hd["hdms"],"hdzp"=>$hd["hdzp"]]);
    }

    /**
     * 市场活动反馈通过
     */
    public function schdfktg(){
        $fb_brief = $this->request->param('fb_brief');
        $id = $this->request->param('id');
        $bool = db('cg_ti_list')->where('id',$id)->update([
           'fb_brief'=>$fb_brief,
           'fb_time'=>time(),
           'fb_user'=>session('employee_id'),
        ]);
        if(false!==$bool){
            echo json_encode(['success'=>1,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>0,'msg'=>'error']);
        }
    }

    /**
     * 经销商市场费用对账单
     */
    public function jxsscfydzd(){
        $where = [];
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('cg_jxs')->field("id,sn,title")->select();
       // print_r($dg);exit;
        foreach ($dg as $k => $v) {
            # code...
            $ypf=db("cg_ti t")->join("cg_ti_list td","td.ti_id=t.id")->where("t.jxs_id={$v["id"]} and t.status=7 and (t.status2=0 or t.status2 is null)")->field("yjsjtrfy,fb_shijitourufeiyong")->select();
            $dg[$k]["ypf"]=0;
            foreach ($ypf as $k1 => $v1) {
                # code...
                if($v1["fb_shijitourufeiyong"])
                    $dg[$k]["ypf"]+=$v1["fb_shijitourufeiyong"];
                else
                    $dg[$k]["ypf"]+=$v1["yjsjtrfy"];
            }
            $yhx=db("cg_ti_hexiao")->where("status=7")->sum("tax");
            if($yhx)
                $dg[$k]["yhx"]=$yhx;
            else
                $dg[$k]["yhx"]=0;
            $whx_sqz=db("cg_ti_hexiao")->where("status in (1,2,3,4,5,6)")->sum("tax");
            if($yhx)
                $dg[$k]["whx_sqz"]=$yhx;
            else
                $dg[$k]["whx_sqz"]=0;
            $dg[$k]["byhx"]=db("cg_ti t")->join("cg_ti_list td","td.ti_id=t.id")->where("t.jxs_id={$v["id"]} and t.status=7 and (t.status2=0 or t.status2 is null)")->sum("hx_byhx");
            if(!$dg[$k]["byhx"])
                $dg[$k]["byhx"]=0;
            $dg[$k]["whx_wsq"]=$dg[$k]["ypf"]-$dg[$k]["yhx"]-$dg[$k]["whx_sqz"]-$dg[$k]["byhx"];
            if($dg[$k]["whx_wsq"]<0)$dg[$k]["whx_wsq"]=0;
        }
        echo json_encode($dg);
    }
    /**
     * 经销商市场费用对账单明细
     */
    public function jxsscfydzdmx(){
        $id = $this->request->param('id');
        $dg = db('cg_ti_list')->where('id',$id)->find();
        echo json_encode($dg);
    }

    /**
     * ti费用核销查询
     */
    public function tifyhxcx(){
        $where = [];
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('cg_ti_hexiao')->where($where)->limit(($page-1)*10,10)->select();
        foreach ($dg as $k => $v) {
            # code...
            $dg[$k]["jxs"]=db("cg_jxs")->where(["id"=>$v["jxs_id"]])->value("title");
            $dg[$k]["status"]=db("cg_ti_hexiao_status")->where(["id"=>$v["status"]])->value("title");
            $dg[$k]["ctime"]=date("Y-m-d H:i:s",$dg[$k]["ctime"]);
        }
        echo json_encode($dg);
    }

    /**
     * 销售进度--本月
     */
    public function xsjd(){
        $eid = $this->geteid($this->request->param('userid'));
        $where = [];
        $BeginDate=date('Y-m-01', strtotime(date("Y-m-d")));
        $endDate =  date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));
        $today=strtotime(date("Y-m-d"));
        $todayend=$today+24*3600;
        $todaydate=date("Y-m-d");
        //获取当前考核期
        $k1arr=db("cg_kaoheqi1")->where("starttime<=$today and endtime>=$today")->find();
        $k2arr=db("cg_kaoheqi2")->where("starttime<=$today and endtime>=$today")->find();
        $kaohe1=$k1arr["id"];
        $kaohe2=$k2arr["id"];

            //计算天数
            $k1ts=($k1arr["endtime"]-$k1arr["starttime"])/3600/24+1;
            $k2ts=($k2arr["endtime"]-$k2arr["starttime"])/3600/24+1;
        $where['sqrq'] = [['>=',strtotime($BeginDate)],['<=',strtotime($endDate)],'and'];
        $where["status"]=7;
        $je = db('cg_order')->where($where)->where("yszje<>0")->group("cusType,cusName")->field("cusType,cusName,sum(yszje) as yszje")->select();
        $dg["lj"]=0;$channelarr=[];$channelbili=[];
        foreach ($je as $k => $v) {
            # code...
            if($v["cusType"]==1){
                $channeltype=db("cg_jxs")->where("id={$v["cusName"]}")->value("channeltype");
            }else{
                $channeltype=db("cg_net n")->join("cg_system s","n.system_id=s.id")->join("cg_jxs j","s.jxs_id=j.id")->where("n.id={$v["cusName"]}")->value("channeltype");
            }
            if(in_array($channeltype,$channelarr)){
                $channelbili[$channeltype]["jine"]+=$v["yszje"];
            }else{
                $channelbili[$channeltype]=[];
                $channelbili[$channeltype]["channel"]=db("cg_channel_types1")->where("id={$channeltype}")->value("title");
                $channelbili[$channeltype]["jine"]=$v["yszje"];
                $channelarr[]=$channeltype;
            }
            $dg["lj"]+=$v["yszje"];
        }
        if($je){
            $dg["lj"]=round($dg["lj"]/10000,2);
        }else{
            $dg["lj"]=0;
        }
        foreach ($channelbili as $k => $v) {
            # code...
            if($dg["lj"]==0||$v["jine"]==0){
                $channelbili[$k]["bili"]=0;
            }else{
                $channelbili[$k]["jine"]=round($channelbili[$k]["jine"]/10000,2);
                $channelbili[$k]["bili"]=round($channelbili[$k]["jine"]/$dg["lj"]*100,2);
            }
            $dg["qdzb"][]=$channelbili[$k];
        }
        
        $todayje=db('cg_order')->where("status=7 and sqrq>={$today} and sqrq<{$todayend} and yszje<>0 ")->sum("yszje");
        if($todayje){
            $dg["jrdd"]=round($todayje/10000,2);
        }else{
            $dg["jrdd"]=0;
        }
        //集团销售目标
        $jttar=db("target_apply a")
        ->join("target_apply_detail b","b.apply_id=a.id")
        ->where("a.state=7 and a.state2=1 and a.type_id=1 and b.yijikaoheqi=$kaohe1")
        ->field("b.sale,b.yijikaoheqi,b.erjikaoheqi")
        ->select();
        $dg["mb"]=0;
        for($i=0;$i<count($jttar);$i++){
            if($jttar[$i]["erjikaoheqi"]){
                if($jttar[$i]["erjikaoheqi"]==$kaohe2){
                    $dg["mb"]+=$jttar[$i]["sale"];
                }
            }else{
                $dg["mb"]+=$jttar[$i]["sale"]/$k1ts*$k2ts;
            }
        }
        $dg["mb"]=round($dg["mb"]/10000,2);
        //销售进度达成率
        if($dg["mb"]==0||$dg["lj"]==0)
            $dg["jddcl"]=0;
        else
            $dg["jddcl"]=round($dg["lj"]/$dg["mb"]*100,2);
        //品牌占比
        $pinpaibili=db('cg_order as o')->join("cg_order_list od","od.order_id=o.id")
        ->where($where)->where("yszje<>0")->where("od.brand is not null and od.ysje>0")->group("od.brand")->field("od.brand,sum(od.ysje) as jine")->select();
        foreach ($pinpaibili as $k => $v) {
            # code...
            $pinpaibili[$k]["jine"]=round($pinpaibili[$k]["jine"]/10000,2);
            if( $pinpaibili[$k]["jine"]==0||$dg["lj"]==0)
                $pinpaibili[$k]["bili"]=0;
            else
                $pinpaibili[$k]["bili"]=round($pinpaibili[$k]["jine"]/$dg["lj"]*100,2);
        }
        $dg["ppzb"]=$pinpaibili;
        //个人目标6发运，7，回款 8零售
        $gerenmb=db("target_apply a")->join("target_apply_detail ap","ap.apply_id=a.id")->where("a.state=7 and a.state2=1 and a.type_id in (6,7,8) and ap.people=$eid and yijikaoheqi=$kaohe1")->field("type_id,yijikaoheqi,erjikaoheqi,feiyong")->select();
        $dg["Xsjd_fy_mb"]=0;$dg["Xsjd_hk_mb"]=0;$dg["Xsjd_ls_mb"]=0;
        foreach ($gerenmb as $k => $v) {
            # code...
            $tmpsz=0;
            if($v["erjikaoheqi"]){
                $tmpsz+=$v["feiyong"];
            }else{
                $tmpsz+=round($v["feiyong"]/$k1ts*$k2ts,2);
            }
            if($v["type_id"]==6){
                $dg["Xsjd_fy_mb"]+=$tmpsz;
            }else if($v["type_id"]==7){
                $dg["Xsjd_hk_mb"]+=$tmpsz;
            }else {
                $dg["Xsjd_ls_mb"]+=$tmpsz;
            }
        }
        $dg["Xsjd_fy_mb"]=round($dg["Xsjd_fy_mb"]/10000,2);
        $dg["Xsjd_hk_mb"]=round($dg["Xsjd_hk_mb"]/10000,2);
        $dg["Xsjd_ls_mb"]=round($dg["Xsjd_ls_mb"]/10000,2);
        //个人回款
        $dg["Xsjd_hk_jrhk"]=0;$dg["Xsjd_hk_lj"]=0;$dg["Xsjd_hk_qk"]=$dg["Xsjd_hk_mb"]-$dg["Xsjd_hk_lj"];
        if($dg["Xsjd_hk_mb"]!=0){
            $dg["Xsjd_hk_bili"]=round($dg["Xsjd_hk_lj"]/$dg["Xsjd_hk_mb"],2);
        }else{
            $dg["Xsjd_hk_bili"]=0;
        }
        //个人订单
        $geren=db('cg_order')->where($where)->where("yszje<>0 and sqr=$eid")->sum("yszje");
        if($geren){
            $dg["Xsjd_ls_lj"]=round($geren/10000,2);
        }else{
            $dg["Xsjd_ls_lj"]=0;
        }
        $gerenjinri=db('cg_order')->where($where)->where("yszje<>0 and sqr=$eid and sqrq>={$today} and sqrq<{$todayend}")->sum("yszje");
        if($gerenjinri){
            $dg["Xsjd_ls_jrls"]=round($gerenjinri/10000,2);
        }else{
            $dg["Xsjd_ls_jrls"]=0;
        }
        $dg["Xsjd_ls_qk"]=$dg["Xsjd_ls_mb"]-$dg["Xsjd_ls_lj"];
        if($dg["Xsjd_ls_mb"]){
            $dg["Xsjd_ls_bili"]=round($dg["Xsjd_ls_lj"]/$dg["Xsjd_ls_mb"]*100,2);
        }else{
            $dg["Xsjd_ls_bili"]=0;
        }
        //个人发运
        $gefy=db("bx_fy")->where("salesman_id=$eid and fyDate>='{$BeginDate}' and fyDate<='{$endDate}'")->sum("fyZheMoney");
        if($gefy){
            $dg["Xsjd_fy_lj"]=round($gefy/10000,2);
        }else{
            $dg["Xsjd_fy_lj"]=0; 
        }

        $gejrfy=db("bx_fy")->where("salesman_id=$eid and fyDate='{$todaydate}'")->sum("fyZheMoney");
        if($gejrfy){
            $dg["Xsjd_fy_Jrfy"]=round($gejrfy/10000,2);
        }else{
            $dg["Xsjd_fy_Jrfy"]=0; 
        }
        $dg["Xsjd_fy_qk"]=$dg["Xsjd_fy_mb"]-$dg["Xsjd_fy_lj"];
        if($dg["Xsjd_fy_mb"]){
            $dg["Xsjd_fy_bili"]=round($dg["Xsjd_fy_lj"]/$dg["Xsjd_fy_mb"]*100,2);
        }else{
            $dg["Xsjd_fy_bili"]=0;
        }
        //导购部分
        $dg["Xsjd_dg_mb"]=0;
        $dg["Xsjd_dg_jrhb"]=0;
        $dg["Xsjd_dg_bzhb"]=0;
        $dg["Xsjd_db_lj"]=0;
        $dg["Dgrs"]=0;
        $dg["Ljrj"]=0;
        $dg["Fyjd_ti_gr"]=0;
        $dg["Fyjd_ti_xq"]=0;
        $dg["Fyjd_rc_gr"]=0;
        $dg["Fyjd_rc_xq"]=0;
        $dg["Xsjd_dg_ls_bili"]=0;
        $dg["Xsjd_dg_bili"]=0;
        $dg["Eqdzb"]=[];$dg["Ppzb"]=[];
        echo json_encode($dg);
    }

    /**
     * 销售进度--本季
     */
    public function xsjdbj(){
         $eid = $this->geteid($this->request->param('userid'));
        $where = [];
        $season = ceil((date('n'))/3);//当月是第几季度
        $BeginDate = date('Y-m-d H:i:s', mktime(0, 0, 0,$season*3-3+1,1,date('Y')));
        $endDate = date('Y-m-d H:i:s', mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y')));
        $today=strtotime(date("Y-m-d"));
        $todayend=$today+24*3600;
        $todaydate=date("Y-m-d");
        //获取当前考核期
        $k1arr=db("cg_kaoheqi1")->where("starttime<=$today and endtime>=$today")->find();
        $kaohe1=$k1arr["id"];
        $where['sqrq'] = [['>=',strtotime($BeginDate)],['<=',strtotime($endDate)],'and'];
        $where["status"]=7;
        $je = db('cg_order')->where($where)->where("yszje<>0")->group("cusType,cusName")->field("cusType,cusName,sum(yszje) as yszje")->select();
        $dg["lj"]=0;$channelarr=[];$channelbili=[];
        foreach ($je as $k => $v) {
            # code...
            if($v["cusType"]==1){
                $channeltype=db("cg_jxs")->where("id={$v["cusName"]}")->value("channeltype");
            }else{
                $channeltype=db("cg_net n")->join("cg_system s","n.system_id=s.id")->join("cg_jxs j","s.jxs_id=j.id")->where("n.id={$v["cusName"]}")->value("channeltype");
            }
            if(in_array($channeltype,$channelarr)){
                $channelbili[$channeltype]["jine"]+=$v["yszje"];
            }else{
                $channelbili[$channeltype]=[];
                $channelbili[$channeltype]["channel"]=db("cg_channel_types1")->where("id={$channeltype}")->value("title");
                $channelbili[$channeltype]["jine"]=$v["yszje"];
                $channelarr[]=$channeltype;
            }
            $dg["lj"]+=$v["yszje"];
        }
        if($je){
            $dg["lj"]=round($dg["lj"]/10000,2);
        }else{
            $dg["lj"]=0;
        }
        foreach ($channelbili as $k => $v) {
            # code...
            if($dg["lj"]==0||$v["jine"]==0){
                $channelbili[$k]["bili"]=0;
            }else{
                $channelbili[$k]["jine"]=round($channelbili[$k]["jine"]/10000,2);
                $channelbili[$k]["bili"]=round($channelbili[$k]["jine"]/$dg["lj"]*100,2);
            }
            $dg["qdzb"][]=$channelbili[$k];
        }
        
        $todayje=db('cg_order')->where("status=7 and sqrq>={$today} and sqrq<{$todayend} and yszje<>0 ")->sum("yszje");
        if($todayje){
            $dg["jrdd"]=round($todayje/10000,2);
        }else{
            $dg["jrdd"]=0;
        }
        //集团销售目标
        $jttar=db("target_apply a")
        ->join("target_apply_detail b","b.apply_id=a.id")
        ->where("a.state=7 and a.state2=1 and a.type_id=1 and b.yijikaoheqi=$kaohe1")
        ->field("b.sale,b.yijikaoheqi")
        ->select();
        $dg["mb"]=0;
        for($i=0;$i<count($jttar);$i++){
           
            $dg["mb"]+=$jttar[$i]["sale"];
           
        }
        $dg["mb"]=round($dg["mb"]/10000,2);
        //销售进度达成率
        if($dg["mb"]==0||$dg["lj"]==0)
            $dg["jddcl"]=0;
        else
            $dg["jddcl"]=round($dg["lj"]/$dg["mb"]*100,2);
        //品牌占比
        $pinpaibili=db('cg_order as o')->join("cg_order_list od","od.order_id=o.id")
        ->where($where)->where("yszje<>0")->where("od.brand is not null and od.ysje>0")->group("od.brand")->field("od.brand,sum(od.ysje) as jine")->select();
        foreach ($pinpaibili as $k => $v) {
            # code...
            $pinpaibili[$k]["jine"]=round($pinpaibili[$k]["jine"]/10000,2);
            if( $pinpaibili[$k]["jine"]==0||$dg["lj"]==0)
                $pinpaibili[$k]["bili"]=0;
            else
                $pinpaibili[$k]["bili"]=round($pinpaibili[$k]["jine"]/$dg["lj"]*100,2);
        }
        $dg["ppzb"]=$pinpaibili;
        //个人目标6发运，7，回款 8零售
        $gerenmb=db("target_apply a")->join("target_apply_detail ap","ap.apply_id=a.id")->where("a.state=7 and a.state2=1 and a.type_id in (6,7,8) and ap.people=$eid and yijikaoheqi=$kaohe1")->field("type_id,yijikaoheqi,feiyong")->select();
        $dg["Xsjd_fy_mb"]=0;$dg["Xsjd_hk_mb"]=0;$dg["Xsjd_ls_mb"]=0;
        foreach ($gerenmb as $k => $v) {
            # code...
            $tmpsz=0;
            
            $tmpsz+=$v["feiyong"];
           
            if($v["type_id"]==6){
                $dg["Xsjd_fy_mb"]+=$tmpsz;
            }else if($v["type_id"]==7){
                $dg["Xsjd_hk_mb"]+=$tmpsz;
            }else {
                $dg["Xsjd_ls_mb"]+=$tmpsz;
            }
        }
        $dg["Xsjd_fy_mb"]=round($dg["Xsjd_fy_mb"]/10000,2);
        $dg["Xsjd_hk_mb"]=round($dg["Xsjd_hk_mb"]/10000,2);
        $dg["Xsjd_ls_mb"]=round($dg["Xsjd_ls_mb"]/10000,2);
         //个人回款
        $dg["Xsjd_hk_jrhk"]=0;$dg["Xsjd_hk_lj"]=0;$dg["Xsjd_hk_qk"]=$dg["Xsjd_hk_mb"]-$dg["Xsjd_hk_lj"];
        if($dg["Xsjd_hk_mb"]!=0){
            $dg["Xsjd_hk_bili"]=round($dg["Xsjd_hk_lj"]/$dg["Xsjd_hk_mb"],2);
        }else{
            $dg["Xsjd_hk_bili"]=0;
        }
        //个人订单
        $geren=db('cg_order')->where($where)->where("yszje<>0 and sqr=$eid")->sum("yszje");
        if($geren){
            $dg["Xsjd_ls_lj"]=round($geren/10000,2);
        }else{
            $dg["Xsjd_ls_lj"]=0;
        }
        $gerenjinri=db('cg_order')->where($where)->where("yszje<>0 and sqr=$eid and sqrq>={$today} and sqrq<{$todayend}")->sum("yszje");
        if($gerenjinri){
            $dg["Xsjd_ls_jrls"]=round($gerenjinri/10000,2);
        }else{
            $dg["Xsjd_ls_jrls"]=0;
        }
        $dg["Xsjd_ls_qk"]=$dg["Xsjd_ls_mb"]-$dg["Xsjd_ls_lj"];
        if($dg["Xsjd_ls_mb"]){
            $dg["Xsjd_ls_bili"]=round($dg["Xsjd_ls_lj"]/$dg["Xsjd_ls_mb"]*100,2);
        }else{
            $dg["Xsjd_ls_bili"]=0;
        }
        //个人发运
        $gefy=db("bx_fy")->where("salesman_id=$eid and fyDate>='{$BeginDate}' and fyDate<='{$endDate}'")->sum("fyZheMoney");
        if($gefy){
            $dg["Xsjd_fy_lj"]=round($gefy/10000,2);
        }else{
            $dg["Xsjd_fy_lj"]=0; 
        }

        $gejrfy=db("bx_fy")->where("salesman_id=$eid and fyDate='{$todaydate}'")->sum("fyZheMoney");
        if($gejrfy){
            $dg["Xsjd_fy_Jrfy"]=round($gejrfy/10000,2);
        }else{
            $dg["Xsjd_fy_Jrfy"]=0; 
        }
        $dg["Xsjd_fy_qk"]=$dg["Xsjd_fy_mb"]-$dg["Xsjd_fy_lj"];
        if($dg["Xsjd_fy_mb"]){
            $dg["Xsjd_fy_bili"]=round($dg["Xsjd_fy_lj"]/$dg["Xsjd_fy_mb"]*100,2);
        }else{
            $dg["Xsjd_fy_bili"]=0;
        }
        //导购部分
        $dg["Xsjd_dg_mb"]=0;
        $dg["Xsjd_dg_jrhb"]=0;
        $dg["Xsjd_dg_bzhb"]=0;
        $dg["Xsjd_db_lj"]=0;
        $dg["Dgrs"]=0;
        $dg["Ljrj"]=0;
        $dg["Fyjd_ti_gr"]=0;
        $dg["Fyjd_ti_xq"]=0;
        $dg["Fyjd_rc_gr"]=0;
        $dg["Fyjd_rc_xq"]=0;
         $dg["Xsjd_dg_ls_bili"]=0;
        $dg["Xsjd_dg_bili"]=0;
        $dg["Eqdzb"]=[];$dg["Ppzb"]=[];
        echo json_encode($dg);
    }

    /**
     * 销售进度--本年
     */
    public function xsjdbn(){
         $eid = $this->geteid($this->request->param('userid'));
        $where = [];
        $BeginDate = date('Y-1-1');
        $endDate = date('Y-12-31');
        $today=strtotime(date("Y-m-d"));
        $todayend=$today+24*3600;
        $todaydate=date("Y-m-d");
        $cnid=db("cg_cainian")->where("starttime<=$today and endtime>=$today")->value("id");
        $where['sqrq'] = [['>=',strtotime($BeginDate)],['<=',strtotime($endDate)],'and'];
        $where["status"]=7;
         $je = db('cg_order')->where($where)->where("yszje<>0")->group("cusType,cusName")->field("cusType,cusName,sum(yszje) as yszje")->select();
        $dg["lj"]=0;$channelarr=[];$channelbili=[];
        foreach ($je as $k => $v) {
            # code...
            if($v["cusType"]==1){
                $channeltype=db("cg_jxs")->where("id={$v["cusName"]}")->value("channeltype");
            }else{
                $channeltype=db("cg_net n")->join("cg_system s","n.system_id=s.id")->join("cg_jxs j","s.jxs_id=j.id")->where("n.id={$v["cusName"]}")->value("channeltype");
            }
            if(in_array($channeltype,$channelarr)){
                $channelbili[$channeltype]["jine"]+=$v["yszje"];
            }else{
                $channelbili[$channeltype]=[];
                $channelbili[$channeltype]["channel"]=db("cg_channel_types1")->where("id={$channeltype}")->value("title");
                $channelbili[$channeltype]["jine"]=$v["yszje"];
                $channelarr[]=$channeltype;
            }
            $dg["lj"]+=$v["yszje"];
        }
        if($je){
            $dg["lj"]=round($dg["lj"]/10000,2);
        }else{
            $dg["lj"]=0;
        }
        foreach ($channelbili as $k => $v) {
            # code...
            if($dg["lj"]==0||$v["jine"]==0){
                $channelbili[$k]["bili"]=0;
            }else{
                $channelbili[$k]["jine"]=round($channelbili[$k]["jine"]/10000,2);
                $channelbili[$k]["bili"]=round($channelbili[$k]["jine"]/$dg["lj"]*100,2);
            }
            $dg["qdzb"][]=$channelbili[$k];
        }
        
        $todayje=db('cg_order')->where("status=7 and sqrq>={$today} and sqrq<{$todayend} and yszje<>0 ")->sum("yszje");
        if($todayje){
            $dg["jrdd"]=round($todayje/10000,2);
        }else{
            $dg["jrdd"]=0;
        }
        //集团销售目标
        $jttar=db("target_apply a")
        ->join("target_apply_detail b","b.apply_id=a.id")
        ->where("a.state=7 and a.state2=1 and a.type_id=1 and b.cainian=$cnid")
        ->field("b.sale,b.cainian")
        ->select();
        $dg["mb"]=0;
        for($i=0;$i<count($jttar);$i++){
           
            $dg["mb"]+=$jttar[$i]["sale"];
           
        }
        $dg["mb"]=round($dg["mb"]/10000,2);
        //销售进度达成率
        if($dg["mb"]==0||$dg["lj"]==0)
            $dg["jddcl"]=0;
        else
            $dg["jddcl"]=round($dg["lj"]/$dg["mb"]*100,2);
           //个人目标6发运，7，回款 8零售
        $gerenmb=db("target_apply a")->join("target_apply_detail ap","ap.apply_id=a.id")->where("a.state=7 and a.state2=1 and a.type_id in (6,7,8) and ap.people=$eid and cainian=$cnid")->field("type_id,feiyong")->select();
        $dg["Xsjd_fy_mb"]=0;$dg["Xsjd_hk_mb"]=0;$dg["Xsjd_ls_mb"]=0;
        foreach ($gerenmb as $k => $v) {
            # code...
            $tmpsz=0;
            
            $tmpsz+=$v["feiyong"];
           
            if($v["type_id"]==6){
                $dg["Xsjd_fy_mb"]+=$tmpsz;
            }else if($v["type_id"]==7){
                $dg["Xsjd_hk_mb"]+=$tmpsz;
            }else {
                $dg["Xsjd_ls_mb"]+=$tmpsz;
            }
        }
        $dg["Xsjd_fy_mb"]=round($dg["Xsjd_fy_mb"]/10000,2);
        $dg["Xsjd_hk_mb"]=round($dg["Xsjd_hk_mb"]/10000,2);
        $dg["Xsjd_ls_mb"]=round($dg["Xsjd_ls_mb"]/10000,2);
          //个人回款
        $dg["Xsjd_hk_jrhk"]=0;$dg["Xsjd_hk_lj"]=0;$dg["Xsjd_hk_qk"]=$dg["Xsjd_hk_mb"]-$dg["Xsjd_hk_lj"];
        if($dg["Xsjd_hk_mb"]!=0){
            $dg["Xsjd_hk_bili"]=round($dg["Xsjd_hk_lj"]/$dg["Xsjd_hk_mb"],2);
        }else{
            $dg["Xsjd_hk_bili"]=0;
        }
        //个人订单
        $geren=db('cg_order')->where($where)->where("yszje<>0 and sqr=$eid")->sum("yszje");
        if($geren){
            $dg["Xsjd_ls_lj"]=round($geren/10000,2);
        }else{
            $dg["Xsjd_ls_lj"]=0;
        }
        $gerenjinri=db('cg_order')->where($where)->where("yszje<>0 and sqr=$eid and sqrq>={$today} and sqrq<{$todayend}")->sum("yszje");
        if($gerenjinri){
            $dg["Xsjd_ls_jrls"]=round($gerenjinri/10000,2);
        }else{
            $dg["Xsjd_ls_jrls"]=0;
        }
        $dg["Xsjd_ls_qk"]=$dg["Xsjd_ls_mb"]-$dg["Xsjd_ls_lj"];
        if($dg["Xsjd_ls_mb"]){
            $dg["Xsjd_ls_bili"]=round($dg["Xsjd_ls_lj"]/$dg["Xsjd_ls_mb"]*100,2);
        }else{
            $dg["Xsjd_ls_bili"]=0;
        }
        //个人发运
        $gefy=db("bx_fy")->where("salesman_id=$eid and fyDate>='{$BeginDate}' and fyDate<='{$endDate}'")->sum("fyZheMoney");
        if($gefy){
            $dg["Xsjd_fy_lj"]=round($gefy/10000,2);
        }else{
            $dg["Xsjd_fy_lj"]=0; 
        }

        $gejrfy=db("bx_fy")->where("salesman_id=$eid and fyDate='{$todaydate}'")->sum("fyZheMoney");
        if($gejrfy){
            $dg["Xsjd_fy_Jrfy"]=round($gejrfy/10000,2);
        }else{
            $dg["Xsjd_fy_Jrfy"]=0; 
        }
        $dg["Xsjd_fy_qk"]=$dg["Xsjd_fy_mb"]-$dg["Xsjd_fy_lj"];
        if($dg["Xsjd_fy_mb"]){
            $dg["Xsjd_fy_bili"]=round($dg["Xsjd_fy_lj"]/$dg["Xsjd_fy_mb"]*100,2);
        }else{
            $dg["Xsjd_fy_bili"]=0;
        }
        //导购部分
        $dg["Xsjd_dg_mb"]=0;
        $dg["Xsjd_dg_jrhb"]=0;
        $dg["Xsjd_dg_bzhb"]=0;
        $dg["Xsjd_db_lj"]=0;
        $dg["Dgrs"]=0;
        $dg["Ljrj"]=0;
        $dg["Fyjd_ti_gr"]=0;
        $dg["Fyjd_ti_xq"]=0;
        $dg["Fyjd_rc_gr"]=0;
        $dg["Fyjd_rc_xq"]=0;
         $dg["Xsjd_dg_ls_bili"]=0;
        $dg["Xsjd_dg_bili"]=0;
        $dg["Eqdzb"]=[];$dg["Ppzb"]=[];
        echo json_encode($dg);
    }



    /**
     * 所属经销商订单查询
     */
    public function ssjxsddcx(){
        $status = $this->request->param('status');
        $where = [];
        if(session('employee_id'))
            $jxs_ids = db('cg_jxs')->where('stuff','like','%"'.session('employee_id').'"%')->column('id');
        else
            $jxs_ids = db('cg_jxs')->column('id');
        //echo db('cg_jxs')->getLastsql();exit;
        $where['cusType']=1;
        $where['cusName']=['in',$jxs_ids];
        if($status)
            $where['status'] = $status;
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('cg_order')->where($where)->limit(($page-1)*10,10)->field('id,khmc,cusType,sn,yszje dhje,fhzt,shzt,status,sqrq,sqr,sqrmc')->select();
        foreach ($dg as $k => $v) {
            # code...
            $dg[$k]["djsl"]=db("cg_order_list")->where(["order_id"=>$v["id"],"xslx"=>1])->sum("num");
        }
        echo json_encode($dg);
    }

    /**
     * 所属经销商订单详情
     */
    public function ssjxsddxq(){
        $id = $this->request->param('id');

        $dg = db('cg_order')->where(['id'=>$id])->find();
        $dg['bm'] = db('department t')->join('department_employee t2','t2.department_id=t.id')->value('de_name');
        $dg['zw'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->value('job_name');
        $dg['ddmx'] = db('cg_order_list')->where('order_id',$id)->select();
        echo json_encode($dg);
    }

    /**
     * 所属经销商对账单
     */
    public function ssjxsdzd(){
        $where = [];
        if(session('employee_id'))
            $where['stuff']=['like','%"'.session('employee_id').'"%'];
       
        
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $dg = db('cg_jxs')->where($where)->limit(($page-1)*10,10)->select();
        echo json_encode($dg);
    }
    /**
     * 所属经销商对账单
     */
    public function ssjxsdzdxq(){
        $id = $this->request->param('id');
        $dg = db('cg_jxs')->where('id',$id)->field('title,sn,id')->find();
        echo json_encode($dg);
    }
    /**
     * 费用对账单汇总
     */
    public function ssjxsfydzdhz(){
       $id = $this->request->param('id');
       //已批准
       $ypz = db('cg_ti t')->join('cg_ti_list t2','t.id=t2.ti_id')->where('t.jxs_id',$id)->sum('pizhunhanshui');
       //已核销
       $yhx = db('cg_ti t')->join('cg_ti_list t2','t.id=t2.ti_id')->where('t.jxs_id',$id)->sum('t2.hx_yihexiao2');
       //核销中
       $hxz = db('cg_ti_hexiao t')->join('cg_ti_hexiao_list t2','t.id=t2.hx_id')->where('t.jxs_id',$id)->sum('t2.shijitourujine');
       //不予核销
       $byhx = db('cg_ti t')->join('cg_ti_list t2','t.id=t2.ti_id')->where('t.jxs_id',$id)->sum('t2.hx_byhx');
       $wsq = $ypz-$yhx-$hxz-$byhx;//未申请
        //已支付金额
        $yzf = db('cg_ti_hexiao t')->join('cg_ti_hexiao_list t2','t.id=t2.hx_id')->where('t.jxs_id',$id)->sum('t.yzfje');
        //待支付
        $dzf = $yhx-$yzf;
        echo json_encode(['ypz'=>$ypz,'yhx'=>$yhx,'hxz'=>$hxz,'byhx'=>$byhx,'wsq'=>$wsq,'yzf'=>$yzf,'dzf'=>$dzf]);
    }
    /**
     * 费用对账单明细
     */
    public function ssjxsfydzdmx(){
        $id = $this->request->param('id');
        //已批准
        $page = $this->request->param('page')?$this->request->param('page'):1;
       /* $data = db('cg_ti t')->where('t.jxs_id',$id)->limit(($page-1)*10,10)->field('t.sn,t.title,t2.pizhunhanshui ypz,t2.hx_yihexiao2 yhx,t2.id list_id,t2.hx_byhx byhx')->select();*/
       $data = db('cg_ti t')->where('t.jxs_id',$id)->limit(($page-1)*10,10)->field('t.id,t.sn,t.title,id')->select();
        foreach($data as $k=>$v){
            $v["ypz"]=db("cg_ti_list")->where(["ti_id"=>$v["id"]])->sum("yjsjtrfy");
            $v['yhx'] = db('cg_ti_hexiao t')->join('cg_ti_hexiao_list t2','t.id=t2.hx_id')->where(['t2.ti_id'=>$v['id'],'t.status'=>7])->sum('t2.shijihexiaojine');
            $v["byhx"]=db("cg_ti_list")->where(["ti_id"=>$v["id"]])->sum("hx_byhx");
            $v['hxz'] = db('cg_ti_hexiao t')->join('cg_ti_hexiao_list t2','t.id=t2.hx_id')->where("t2.ti_id={$v["id"]} and t.status in (3,4,5,6)")->sum('t2.shijihexiaojine');
            $v['wsq'] = $v['ypz']-$v['yhx']-$v['hxz']-$v['byhx'];
            $v['yzf']=0; 
            $yzf= db('cg_ti_hexiao t')->join('cg_ti_hexiao_list t2','t.id=t2.hx_id')->where('t2.ti_id',$v['id'])->group("t.id")->field('t.yzfje')->select();
            if($yzf){
                foreach ($yzf as $k1 => $v1) {
                    # code...
                    $v['yzf']+=$v1["yzfje"];
                }
            }
            $v['dzf'] = $v['yhx']-$v['yzf'];
            $data[$k] = $v;
        }
        echo json_encode($data);
    }

    //货款对账单
    public function dkdzd(){
        $id = $this->request->param('id');
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('yd_dkdzd')->where('jxs',$id)->limit(($page-1)*10,10)->select();
        echo json_encode($data);
    }

    //客户通讯录
    public function khtxl(){
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('yd_khtxl')->limit(($page-1)*10,10)->select();
        echo json_encode($data);
    }

    //客户通讯录详情
    public function khtxlxq(){
        $id = $this->request->param('id');
        $data = db('yd_khtxl')->where('id',$id)->find();
        echo json_encode($data);
    }

    //经销商资料管理
    public function jxszlgl(){
        //$page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('cg_jxs')->field('sn,id,title,addr')->select();
        echo json_encode($data);
    }
    //网点资料
    public function netzlxq(){
        $id = $this->request->param('id');
        $net=db("cg_net")->where(["id"=>$id])->find();
        if($net){
            $sys=db("cg_system")->where(["id"=>$net["system_id"]])->find();
            $jxs=db("cg_jxs")->where(["id"=>$sys["jxs"]])->find();
            $data["id"]=$net["id"];
            $data["net"]=$net["title"];
            $data["sn"]=$net["sn"];
            $data["mysn"]=$net["mysn"];
            $data["sys"]=$sys["title"];
            $data["jxs"]=$jxs["title"];
            $data["cat"]=db("cg_networktype")->where(["id"=>$net["cat"]])->value("title");
            $data["grade"]=db("cg_networklevel")->where(["id"=>$net["grade"]])->value("title");
            $data["iskey"]=$net["iskey"];$data["guide"]=$net["guide"];
            $data["arae"]=$net["area"]; $data["cashiers"]=$net["cashiers"];
            $data["shelf_num"]=$net["shelf_num"];
            $data["starttime"]=date("Y-m-d",$net["starttime"]);
            $data["addr"]=$net["detailAddress"];
            $data["lianxiren"]=db("cg_net_ci")->where(["net_id"=>$net["id"]])->field("name,job,phone,mobile")->find();
            $data["jinchang"]=db("cg_net_barcode")->where("net_id={$net["id"]} and status=0 and tuichang=0")->count();
            if(!$data["jinchang"])
                $data["jinchang"]=0;
            $data["competitor"]=db("cg_net_competitor")->where("net_id={$net["id"]} and isdel=0")->count();
            if(!$data["competitor"])
                $data["competitor"]=0;
            $data["brief"]=$net["brief"];
            $data["dg"]="";
            $data["city"]=db("cg_market_city")->where(["id"=>$net["city"]])->value("title");
            $dg=db("cg_net_dg")->where(["net_id"=>$net["id"]])->select();
            if($dg){
                $dgarr=[];
                foreach ($dg as $k => $v) {
                    # code...
                    $dgarr[]=$v["xm"];
                }
                $data["dg"]=implode(',',$dgarr);
            }
        }else{
            $data=[];
        }
        echo json_encode($data);
    }
    public function netlevel(){
        $data=db("cg_networklevel")->field("id,title")->select();
        echo json_encode($data);
    }
    public function xiugainet(){
        $data["id"] = $this->request->param('id');
        $userid = $this->request->param('userid');
        $data["puser"]=$this->geteid($userid);
        $data["mysn"]=$this->request->param('mysn');
        $data["cat"]=$this->request->param('cat');
        $data["iskey"]=$this->request->param('iskey');
        $data["guide"]=$this->request->param('guide');
        $data["area"]=$this->request->param('area');
        $data["cashiers"]=$this->request->param('cashiers');
        $data["shelf_num"]=$this->request->param('shelf_num');
        $data["starttime"]=strtotime($this->request->param('starttime'));
        $data["grade"]=$this->request->param('grade');
        $data["detailAddress"]=$this->request->param('addr');
        $data["breif"]=$this->request->param('breif');
        $res1=db("cg_net")->update($data);
        $datam["name"]=$this->request->param('lianxiren');
        $datam["mobile"]=$this->request->param('lianxiphone');
        $netlianxi=db("cg_net_ci")->where(["net_id"=>$data["id"]])->find();
        if($netlianxi){
            $datam["id"]=$netlianxi["id"];
            $res2=db("cg_net_ci")->update($datam);
        }else{
            $datam["net_id"]=$data["id"];
            $res2=db("cg_net_ci")->insert($datam);
        }
        if($res1&&$res2){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }

    }
    public function getjxsaddr(){
        $id = $this->request->param('id');
        $sid=db("cg_net")->where(["id"=>$id])->value("system_id");
        $jid=db("cg_system")->where(["id"=>$sid])->value("jxs");
        $data=db("cg_jxs")->where(["id"=>$jid])->field("addr")->find();
        echo json_encode($data);
    }
    //系统资料
    public function systemzlxq(){
        $id = $this->request->param('id');
        $sys=db("cg_system")->where(["id"=>$id])->find();
        if($sys){
            $jxs=db("cg_jxs")->where(["id"=>$sys["jxs"]])->find();
            $data["jxs"]=$jxs["title"];
            $data["title"]=$sys["title"];
            $data["zoning"]=db("cg_market_zoning")->where(["id"=>$jxs["zoning"]])->value("title");
            $data["zoning_fzr"]=db("cg_market_zoning z")->join("employee e","z.head=e.id")->where(["z.id"=>$jxs["zoning"]])->value("e.em_name");
            $data["provice"]=db("cg_market_provice")->where(["id"=>$jxs["provice"]])->value("title");
            $data["provice_fzr"]=db("cg_market_provice z")->join("employee e","z.head=e.id")->where(["z.id"=>$jxs["provice"]])->value("e.em_name");
            $data["city"]=db("cg_market_city")->where(["id"=>$jxs["city"]])->value("title");
            $data["city_fzr"]=db("cg_market_city z")->join("employee e","z.head=e.id")->where(["z.id"=>$jxs["city"]])->value("e.em_name");
            $data["erjiqudao"]=db("cg_channel_types2")->where(["id"=>$sys["twoCType"]])->value("title");
            $data["cusType"]=db("cg_customertype")->where(["id"=>$sys["cusType"]])->value("title");
            $cusman=db("cg_system_ci")->where(["system_id"=>$sys["id"]])->select();
            if($cusman){
                $tmpcus=[];
                foreach ($cusman as $k => $v) {
                    # code...
                    $tmpcus[]=$v["name"];
                }
                $data["cusman"]=implode(',',$tmpcus);

            }else{
                $data["cusman"]="";
            }
            if($sys["stuff"]){
               $stuff=unserialize($sys["stuff"]);
                $tmp=[];
                foreach ($stuff as $k => $v) {
                    # code...
                    $tmp[]=db("employee")->where(["id"=>$v])->value("em_name");
                }
                $data["stuff"]=implode(',',$tmp);
            }else{
                $data["stuff"]="";
            }
            $data["addr"]=$sys["detailAddress"];
            $data["brief"]=$sys["brief"];
        }else{
            $data=[];
        }
        echo json_encode($data);
        
    }
    //经销商资料详情
    public function jxszlxq(){
        $id = $this->request->param('id');
        $jxs = db('cg_jxs')->where('id',$id)->find();
        $data["title"]=$jxs["title"];
        $data["sn"]=$jxs["sn"];
        $data["zoning"]=db("cg_market_zoning")->where(["id"=>$jxs["zoning"]])->value("title");
        $data["zoning_fzr"]=db("cg_market_zoning z")->join("employee e","z.head=e.id")->where(["z.id"=>$jxs["zoning"]])->value("e.em_name");
        $data["provice"]=db("cg_market_provice")->where(["id"=>$jxs["provice"]])->value("title");
        $data["provice_fzr"]=db("cg_market_provice z")->join("employee e","z.head=e.id")->where(["z.id"=>$jxs["provice"]])->value("e.em_name");
        $data["city"]=db("cg_market_city")->where(["id"=>$jxs["city"]])->value("title");
        $data["city_fzr"]=db("cg_market_city z")->join("employee e","z.head=e.id")->where(["z.id"=>$jxs["city"]])->value("e.em_name");
        $data["cooptime"]=date("Y-m-d",$jxs["cooptime"]);
        $data["channeltype"]=db("cg_channel_types1")->where(["id"=>$jxs["channeltype"]])->value("title");
        $data["direct"]=$jxs["direct"];
        $data["types"]=db("cg_jxs_types")->where(["id"=>$jxs["types"]])->value("title");
        $nowtime=strtotime(date("Y-m-d"));
        $cid=db("cg_cainian")->where("starttime<=$nowtime and endtime>=$nowtime")->value("id");
        $data["xsmb"]=0;
        $mb=db("target_apply t")->join("target_apply_detail td","td.apply_id=t.id")->where("t.type_id=5 and t.state=7 and t.tag<>1 and td.cainian=$cid")->sum("feiyong");
        if($mb){
            $data["xsmb"]=round($mb,2);
        }
        $cainian=db("cg_cainian")->where(["id"=>$cid])->find();
        $cainian["endtime"]=$cainian["endtime"]+3600*24;
        $data["sjdc"]=0;
        $sjdc=db("cg_ti t")->join("cg_ti_list td","td.ti_id=t.id")->where("t.status=7 and (t.status2 is null or t.status2=0) and td.start>={$cainian["starttime"]} and td.end<{$cainian["endtime"]} and t.type_id<>1")->field("td.totalExpectedSales,td.fb_shijixiaoliang")->select();
        foreach ($sjdc as $k => $v) {
            # code...
            if($v["fb_shijixiaoliang"]){
                $data["sjdc"]+=$v["fb_shijixiaoliang"];
            }else{
                $data["sjdc"]+=$v["totalExpectedSales"];
            }
        }
        
        $data["fymb"]=0;
        $mb=db("target_apply t")->join("target_apply_detail td","td.apply_id=t.id")->where("t.type_id=2 and t.state=7 and t.tag<>1 and td.cainian=$cid")->sum("feiyong");
        if($mb){
            $data["fymb"]=round($mb,2);
        }
        $data["sjhf"]=0;
        $sjhf=db("cg_ti t")->join("cg_ti_list td","td.ti_id=t.id")->where("t.status=7 and (t.status2 is null or t.status2=0) and td.start>={$cainian["starttime"]} and td.end<{$cainian["endtime"]}")->field("td.yjsjtrfy,td.fb_shijitourufeiyong")->select();
        foreach ($sjhf as $k => $v) {
            # code...
            if($v["fb_shijitourufeiyong"]){
                $data["sjhf"]+=$v["fb_shijitourufeiyong"];
            }else{
                $data["sjhf"]+=$v["yjsjtrfy"];
            }
        }
        $data["addr"]=$jxs["addr"];
        if($jxs["stuff"]){
            $stuff=unserialize($jxs["stuff"]);
            $tmp=[];
            foreach ($stuff as $k => $v) {
                # code...
                $tmp[]=db("employee")->where(["id"=>$v])->value("em_name");
            }
            $data["stuff"]=implode(',',$tmp);
        }else{
            $data["stuff"]="";
        }
        
        echo json_encode($data);
    }
    //经销商价格
    public function jxsprice(){
        $id = $this->request->param('id');
        $pro=db("pro_products")->where("is_actived=1 and is_deleted=0")->field("id,pro_name,pro_no,unit,box_num")->select();
        foreach ($pro as $k => $v) {
            # code...
            $price=db("pro_price")->where("pid={$v["id"]}")->value("factory");
            $boxprice=db("pro_price")->where("pid={$v["id"]}")->value("box_factory");

            $gid=db("price_group_jxs pj")->join("pro_price_group p","pj.gid=p.id")->where("pj.jid=$id")->value("pj.gid");
            if($gid){
                $now=date("Y-m-d");
                $gp=db("price_group_product")->where("pid={$v["id"]} and gid=$gid and start_time<='$now' and end_time>='$now'")->find();
                if($gp){
                    $price=$gp["lingshou_price"];
                    $boxprice=$gp["fayun_price"];
                }
                   
            }
            $pro[$k]["price"]=$price;
            $pro[$k]["boxprice"]=$boxprice;
        }
        echo json_encode($pro);
    }
    //经销商数据采集
    public function jxssjcj(){
        $data = [];
        $data['addr'] = $this->request->param('addr');
        $data['zp'] = $this->request->param('zp');
        $bool = db('cg_jxs')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }

    //系统资料管理
    public function xtzlgl(){
        $data = db('cg_system')->field('sn,id,title')->select();
        echo json_encode($data);
    }

    //填写系统资料
    public function txxtzl(){

        $data = Request::instance()->post();
        $bool = db('cg_system')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }

    //网点资料管理
    public function wdzlgl(){
        $data = db('cg_net')->field('sn,id,title,guide,iskey,detailAddress as addr')->select();
        echo json_encode($data);
    }
    //竞品品类
    public function procategory(){
        $data=db("competitor_category")->where("is_actived=1 and is_deleted=0")->field("id,category_name,category_no")->select();
        echo json_encode($data);
    }
    //返回竞品
    public function backcompitor(){
        $nid=$this->request->param('net_id');
        $cat=$this->request->param('cat');
        $arr=db("cg_net_competitor")->where(["net_id"=>$nid,"isdel"=>0])->column("name");
        if($arr){
            $str=implode(',',$arr);
            $competitor=db("competitor")->where("id not in ($str) and category_id=$cat and is_actived=1 and is_deleted=0")->field("c_name,id,format")->select();
        }else
        {
            $competitor=db("competitor")->where("is_actived=1 and is_deleted=0 and category_id=$cat")->field("c_name,id,format")->select();
        }
        echo json_encode($competitor);
    }
    //添加竞品
    public function newcategory(){
        $data["name"] = $this->request->param('cid');
        $data["price"] = $this->request->param('price');
        $data["specs"]=db("competitor")->where(["id"=>$data["name"]])->value("format");
        $data["status"]=$this->request->param('status');
        $data["brief"]=$this->request->param('brief');
        $data["net_id"]=$this->request->param('net_id');
        $bool=db("cg_net_competitor")->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    //网点竞品列表
    public function net_competitor(){
        $net_id=$this->request->param('net_id');
        $com=db("cg_net_competitor")->where(["isdel"=>0,"net_id"=>$net_id])->select();
        $data=[];
        foreach ($com as $k => $v) {
            # code...
            $data[$k]["c_name"]=db("competitor")->where(["id"=>$v["name"]])->value("c_name");
            $data[$k]["specs"]=$v["specs"];
            $data[$k]["brief"]=$v["brief"];
            $data[$k]["price"]=$v["price"];
            $data[$k]["status"]=$v["status"];
            $cate=db("competitor")->where(["id"=>$v["name"]])->value("category_id");
            $data[$k]["cate"]=db("competitor_category")->where(["id"=>$cate])->value("category_name");
        }
        echo json_encode($data);
    }
    //网点已进场条码
    public function wdyjc(){
        $id = $this->request->param('id');
        $data=db("cg_net_barcode")->where(["net_id"=>$id,"isdel"=>0,"tuichang"=>0])->field("prod,status,retailPrice,beizhu")->select();
        foreach ($data as $k => $v) {
            # code...
            $data[$k]["unit"]=db("pro_products")->where(["id"=>$v["prod"]])->value("unit");
            $data[$k]["prod"]=db("pro_products")->where(["id"=>$v["prod"]])->value("pro_name");
            
        }
        echo json_encode($data);
    }
    //网点申请中
    public function wdsqz(){
        $id = $this->request->param('id');
        $data=db("cg_ti t")->join("cg_ti_list td","td.ti_id=t.id")->where("t.type_id=1 and t.status in (0,1,3,4,5,6) and td.net_id=$id")->field("td.f1 as prod,t.status,f5 as retailPrice,td.fb_shijitourufeiyong as infee")->select();
        //print_r($data);
        foreach ($data as $k => $v) {
            # code...
            $data[$k]["unit"]=db("pro_products")->where(["id"=>$v["prod"]])->value("unit");
            $data[$k]["prod"]=db("pro_products")->where(["id"=>$v["prod"]])->value("pro_name");
            switch ($v["status"]) {
                case '3':
                    # code...
                    $data[$k]["status"]="区域领导审批";
                    break;
                case '4':
                    # code...
                    $data[$k]["status"]="拆分人审批";
                    break;
                case '5':
                    # code...
                    $data[$k]["status"]="集团领导审批";
                    break;
                case '6':
                    # code...
                    $data[$k]["status"]="抄送";
                    break;
                case '1':
                    # code...
                    $data[$k]["status"]="草稿";
                    break;
                default:
                    # code...
                    $data[$k]["status"]="草稿";
                    break;
            }
        }
        echo json_encode($data);
    }

    //进场条码添加
    public function addtm(){
        $id = $this->request->param('id');
        $pid = $this->request->param('pid');
        $inday = $this->request->param('inday');
        $infee = $this->request->param('infee');
        $price = $this->request->param('price');
        $zp = $this->request->param('zp');
        $bool=true;
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    public function getpro(){
        $data=db("pro_products")->where(["is_deleted"=>0,"is_actived"=>1])->field("id,pro_name")->select();
        echo json_encode($data);
    }
    //填写网点资料
    public function txwdzl(){

        $data = Request::instance()->post();
        $bool = db('cg_net')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    //网点数据采集
    public function netsjcj(){
        $id=$this->request->param('id');
        $zp = $this->request->param('zp');
        $addr=$this->request->param('addr');
        $userid=$this->request->param('userid');
         $data["cuser"]=db("employee")->where(["em_name"=>$userid])->value("id");
        $data["net_id"]=$id;
        $data["zp"]=$zp;
        $data["addr"]=$addr;
        $data["ctime"]=time();
        $bool = db('yd_net_sjcj')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    //系统数据采集
    public function syssjcj(){
        $id=$this->request->param('id');
        $zp = $this->request->param('zp');
        $addr=$this->request->param('addr');
        $userid=$this->request->param('userid');
        $data["cuser"]=db("employee")->where(["em_name"=>$userid])->value("id");
        $data["sys_id"]=$id;
        $data["zp"]=$zp;
        $data["addr"]=$addr;
        $data["ctime"]=time();
        $bool = db('yd_sys_sjcj')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    //下属考勤查询--月报表
    public function xskqcxybb(){
        $yue = $this->request->param('yue');
        $zjxs = $this->request->param('zjxs');
        $userid = $this->request->param('userid');
        $where = [];
        if($zjxs)
            $where['date'] = ['like',$yue.'%'];
        $page = $this->request->param('page')?$this->request->param('page'):1;
        //下属
        if($userid)
            $eid=db("employee")->where("em_name='$userid'")->value("id");
        else
            $eid=session('employee_id');
        $job_id = db('job_employee')->where('employee_id',$eid)->value('job_id');

        if($zjxs==1)
            $job_ids = db('job')->where('path','like','%['.$job_id.']%')->column('id');
        else
            $job_ids = db('job')->where('path','like','%['.$job_id.']')->column('id');

        $em_ids = db('job_employee')->where('job_id','in',$job_ids)->column('employee_id');
        $where['em_id'] = ['in',$em_ids];
        $data = db('yd_kq_log')->where($where)->limit(($page-1)*10,10)->group("em_id")->field("em_id,em_name as xm")->select();
        foreach ($data as $k=> $v) {
            # code...
            $data[$k]["cq"]=db('yd_kq_log')->where("`date` like '{$yue}%' and em_id={$v["em_id"]}")->count();
            $data[$k]["cd"]=db('yd_kq_log')->where("`date` like '{$yue}%' and em_id={$v["em_id"]} and cdfz>0")->count();
            if(!$data[$k]["cd"])
                 $data[$k]["cd"]=0;
            $data[$k]["zt"]=db('yd_kq_log')->where("`date` like '{$yue}%' and em_id={$v["em_id"]} and ztfz>0")->count();
            if(!$data[$k]["zt"])
                 $data[$k]["zt"]=0;
            $data[$k]["qj"]=0;
        }
        echo json_encode($data);
    }
    //下属考勤查询--日报表
    public function xskqcxrbb(){
        $day = $this->request->param('day');
        $zjxs = $this->request->param('zjxs');
         $userid = $this->request->param('userid');
        $where = [];
        if($zjxs)
            $where['date'] = $day;
        $page = $this->request->param('page')?$this->request->param('page'):1;
        //下属
         if($userid)
            $eid=db("employee")->where("em_name='$userid'")->value("id");
        else
            $eid=session('employee_id');
        $job_id = db('job_employee')->where('employee_id',$eid)->value('job_id');
        if($zjxs==1)
            $job_ids = db('job')->where('path','like','%['.$job_id.']%')->column('id');
        else
            $job_ids = db('job')->where('path','like','%['.$job_id.']')->column('id');

        $em_ids = db('job_employee')->where('job_id','in',$job_ids)->column('employee_id');
        $where['em_id'] = ['in',$em_ids];
        $data = db('yd_kq_log')->where($where)->limit(($page-1)*10,10)->group("em_id")->field("em_id,em_name as xm")->select();
        foreach ($data as $k=> $v) {
            # code...
            $data[$k]["cq"]=db('yd_kq_log')->where("`date`='{$yue}' and em_id={$v["em_id"]}")->count();
            $data[$k]["cd"]=db('yd_kq_log')->where("`date`='{$yue}' and em_id={$v["em_id"]} and cdfz>0")->count();
            if(!$data[$k]["cd"])
                 $data[$k]["cd"]=0;
            $data[$k]["zt"]=db('yd_kq_log')->where("`date`='{$yue}' and em_id={$v["em_id"]} and ztfz>0")->count();
            if(!$data[$k]["zt"])
                 $data[$k]["zt"]=0;
            $data[$k]["qj"]=0;
        }
        echo json_encode($data);
    }
    //下属工作日报
    public function xsgzrb(){
        $em_bm = $this->request->param('em_bm');
        $rq = $this->request->param('rq');
        $where = [];
        if($em_bm){
            $where['em_bm'] = ['like','%'.$em_bm.'%'];
        }
        if($rq){
            $where['rq'] = ['like','%'.$rq.'%'];
        }
        $userid=$this->request->param('userid');
        //echo $userid;
        if($userid){
            $eid=$this->geteid($userid);
        }else
        {
            $eid=session('employee_id');
        }
       //echo $eid;
        $page = $this->request->param('page')?$this->request->param('page'):1;
        //下属
        $job_id = db('job_employee')->where('employee_id',$eid)->value('job_id');

        $job_ids = db('job')->where('path','like','%['.$job_id.']')->column('id');

        $em_ids = db('job_employee')->where('job_id','in',$job_ids)->column('employee_id');
        $where['em_id'] = ['in',$em_ids];
        $data = db('yd_gzrb')->where($where)->limit(($page-1)*10,10)->select();
        echo json_encode($data);
    }
    public function geteid($userid){
        $eid=db("employee")->where("em_name='{$userid}'")->value("id");
        return $eid;
    }
    //下属工作日报--点赞
    public function dz(){
        $id = $this->request->param('id');
        $bool = db('yd_gzrb')->where('id',$id)->setInc('dzs');
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    //下属工作日报--评论
    public function pl(){
        $id = $this->request->param('id');
        $data = [];
        $data['gzrb_id'] = $id;
        $data['content'] = $this->request->param('content');
        $data['em_id'] = session('employee_id');
        $bool = db('yd_gzrb_pl')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }

    /**
     * 下属经销商拜访
     */
    public function xsjxsbf(){
        $bgrq = $this->request->param('bgrq');
        $bfr_name = $this->request->param('bfr_name');
        $userid=$this->request->param('userid');
        $where = [];
        if($bgrq){
            $where['bgrq'] = $bgrq;
        }
        if($bfr_name){
            $where['bfr_name'] = $bfr_name;
        }
        $page = $this->request->param('page')?$this->request->param('page'):1;
        if($userid)
            $eid=$this->geteid($userid);
        else
            $eid=session('employee_id');
        //下属
        $job_id = db('job_employee')->where('employee_id',$eid)->value('job_id');

        $job_ids = db('job')->where('path','like','%['.$job_id.']')->column('id');

        $em_ids = db('job_employee')->where('job_id','in',$job_ids)->column('employee_id');
        $where['bfr'] = ['in',$em_ids];
        $data = db('yd_jxsbf')->where($where)->group("bfr")->limit(($page-1)*10,10)->field("bfr as id,bfr_name as xm")->select();
        foreach ($data as $k => $v) {
            # code...
            $count=db('yd_jxsbf')->where("bgrq='{$bgrq}' and bfr={$v["id"]}")->count();
            if($count)
                $data[$k]["bfjxssl"]=$count;
            else
                $data[$k]["bfjxssl"]=0;
        }
        echo json_encode($data);
    }

    /**
     * 下属经销商拜访详情
     */
    public function xsjxsbflb(){
        $id = $this->request->param('id');
        $bgrq = $this->request->param('bgrq');
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('yd_jxsbf')->where("bfr=$id and bgrq='$bgrq'")->limit(($page-1)*10,10)->field("id,jxs_title,qdsj,qtsj,ys,qddz as qdjl,qdjlpc as jlpc,qdpz as qdzp")->select();
        echo json_encode($data);
    }
    public function jxsbfdz(){
        $id = $this->request->param('id');
        $userid=$this->request->param('userid');
        $bool = db('yd_jxsbf')->where(["id"=>$id])->setInc('dz');
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    public function jxsbfpl(){
        $id = $this->request->param('id');
        $userid=$this->request->param('userid');
        $content=$this->request->param('content');
        $data["bfid"]=$id;
        $data["content"]=$content;
        $data["ctime"]=date("Y-m-d H:i:s");
        $data["eid"]=$this->geteid($userid);
        $data["em_name"]=$userid;
        $bool=db("yd_jxsbf_pl")->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    public function jxsbfplck(){
        $id = $this->request->param('id');
        $data=db("yd_jxsbf_pl")->where(["bfid"=>$id])->order("ctime")->field("em_name,ctime,content")->select();
        echo json_encode($data);
    }
    /**
     * 下属网点拜访报表-月报表
     */
    public function xswdbfbb(){
        $yue = $this->request->param('yue');
        $zjxs = $this->request->param('zjxs');
        $where = '';
        
        $where="ddsj like '$yue%' or rq like '$yue%'";

        $page = $this->request->param('page')?$this->request->param('page'):1;
        $userid=$this->request->param('userid');
        //echo $userid;
        if($userid){
            $eid=$this->geteid($userid);
        }else
        {
            $eid=session('employee_id');
        }
        //下属
        $job_id = db('job_employee')->where('employee_id',$eid)->value('job_id');
        if($zjxs==1)
            $job_ids = db('job')->where('path','like','%['.$job_id.']%')->column('id');
        else
            $job_ids = db('job')->where('path','like','%['.$job_id.']')->column('id');

        $em_ids = db('job_employee')->where('job_id','in',$job_ids)->column('employee_id');
        if($em_ids){
            $str=implode(',',$em_ids);
            $where.=" and bfr in ($str)";
        }else{
            $where.="and 1<>1";
        }
        $data = db('yd_wdbf')->where($where)->limit(($page-1)*10,10)->group("bfr")->field("bfr id")->select();
        foreach ($data as $k => $v) {
            # code...
            $data[$k]["xm"]=db("employee")->where(["id"=>$v["id"]])->value("em_name");
            $jh=db('yd_wdbf')->where("rq like '{$yue}%' and bfr={$v["id"]}")->count();
            if($jh)
                $data[$k]["jh"]=$jh;
            else
                $data[$k]["jh"]=0;
            $sj=db('yd_wdbf')->where("ddsj like '{$yue}%' and rq like '{$yue}%' and bfr={$v["id"]}")->count();
            if($sj)
                $data[$k]["sj"]=$sj;
            else
                $data[$k]["sj"]=0;
            $sf=db('yd_wdbf')->where("ddsj is null and rq like '{$yue}%' and bfr={$v["id"]}")->count();
            if($sf)
                $data[$k]["sf"]=$sf;
            else
                $data[$k]["sf"]=0;

            $zong=db('yd_wdbf')->where("ddsj like '{$yue}%' and bfr={$v["id"]}")->count();
            if($zong)
                $data[$k]["jhw"]=$zong-$data[$k]["sj"];
            else
                $data[$k]["jhw"]=0;

        }
        echo json_encode($data);
    }

    /**
     * 下属网点拜访报表-日报表
     */
    public function xswdbfbbrbb(){
        $yue = $this->request->param('day');
        $zjxs = $this->request->param('zjxs');
        $where = '';
        
            $where="ddsj like '$yue%' or rq='$yue'";
            
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $userid=$this->request->param('userid');
        //echo $userid;
        if($userid){
            $eid=$this->geteid($userid);
        }else
        {
            $eid=session('employee_id');
        }
        //下属
        $job_id = db('job_employee')->where('employee_id',$eid)->value('job_id');
        if($zjxs==1)
            $job_ids = db('job')->where('path','like','%['.$job_id.']%')->column('id');
        else
            $job_ids = db('job')->where('path','like','%['.$job_id.']')->column('id');

        $em_ids = db('job_employee')->where('job_id','in',$job_ids)->column('employee_id');
        if($em_ids){
            $str=implode(',',$em_ids);
            $where.=" and bfr in ($str)";
        }else{
            $where.="and 1<>1";
        }
        $data = db('yd_wdbf')->where($where)->limit(($page-1)*10,10)->group("bfr")->field("bfr id")->select();
        foreach ($data as $k => $v) {
            # code...
            $data[$k]["xm"]=db("employee")->where(["id"=>$v["id"]])->value("em_name");
            $jh=db('yd_wdbf')->where("rq ='{$yue}' and bfr={$v["id"]}")->count();
            if($jh)
                $data[$k]["jh"]=$jh;
            else
                $data[$k]["jh"]=0;
            $sj=db('yd_wdbf')->where("ddsj like '{$yue}%' and rq ='{$yue}' and bfr={$v["id"]}")->count();
            if($sj)
                $data[$k]["sj"]=$sj;
            else
                $data[$k]["sj"]=0;
            $sf=db('yd_wdbf')->where("ddsj is null and rq ='{$yue}' and bfr={$v["id"]}")->count();
            if($sf)
                $data[$k]["sf"]=$sf;
            else
                $data[$k]["sf"]=0;

            $zong=db('yd_wdbf')->where("ddsj like '{$yue}%' and bfr={$v["id"]}")->count();
            if($zong)
                $data[$k]["jhw"]=$zong-$data[$k]["sj"];
            else
                $data[$k]["jhw"]=0;

        }
        echo json_encode($data);
    }

    /**
     * 下属网点拜访报表详情
     */
    public function xswdbfbbxq(){
        $id = $this->request->param('id');
        $data = db('yd_wdbf')->where('id',$id)->find();
        echo json_encode($data);
    }

    /**
     * 下属拜访轨迹
     */
    public function xsbfgj(){
        $em_name = $this->request->param('em_name');
        $where = [];
        if($em_name){
            $where['em_name'] = ['like',$em_name];
        }
        $userid=$this->request->param('userid');
        //echo $userid;
        if($userid){
            $eid=$this->geteid($userid);
        }else
        {
            $eid=session('employee_id');
        }
        //下属
        $job_id = db('job_employee')->where('employee_id',$eid)->value('job_id');
        $job_ids = db('job')->where('path','like','%['.$job_id.']%')->column('id');
        $em_ids = db('job_employee')->where('job_id','in',$job_ids)->column('employee_id');
        $where['id'] = ['in',$em_ids];
        $data = db('employee')->where($where)->select();
        foreach($data as $k=>$v){
            $v['bm'] = db('department t')->join('department_employee t2','t2.department_id=t.id')->where('t2.employee_id',$v['id'])->value('de_name');
            $v['gw'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$v['id'])->value('job_name');
            $data[$k] = $v;
        }
        echo json_encode($data);
    }
    /**
     * 下属拜访轨迹详情
     */
    public function xsbfgjxq(){
        $id = $this->request->param('id');
        $em = db('employee t')->join('department_employee t2','t.id=t2.employee_id','left')->join('department t3','t3.id=t2.department_id',"LEFT")->where('t.id',$id)->field('t.em_name,t3.de_name')->find();
        $rq = $this->request->param('rq');
        if(!$rq){
            $rq = date('Y-m-d');
        }
        //签到数量小计
        $qdslxj = db('yd_qdhb')->where(['qdrq'=>$rq,'qdr'=>$id])->count();

        //拜访小计
        //经销商数量
        $sl_jxs = db('yd_jxsbf')->where(['bfr'=>$id,'bgrq'=>$rq])->count();
        $sl_wd = db('yd_wdbf')->where(['bfr'=>$id,'rq'=>$rq])->count();
        $sl_qdhb = db('yd_qdhb')->where(['qdr'=>$id,'qdrq'=>$rq])->count();
        $sl_schd = db('yd_schdbf')->where(['hbr'=>$id,'dwrq'=>$rq])->count();
        $sl_kq = db('yd_kq_log')->where(['em_id'=>$id,'date'=>$rq])->count();
        $qdslxj=$sl_jxs +$sl_wd+$sl_qdhb+$sl_schd+$sl_kq ;
        //已拜访客户
        $where="bfr=$id and rq='{$rq}' and ddsj is not null";
        $ybfkh = db('yd_wdbf')->where($where)->field('wdmc,ddsj,qddd,syzjl')->select();

        //失访客户
        $where="bfr=$id and rq='{$rq}' and ddsj is null";
        $sfkh = db('yd_wdbf')->where($where)->field('wdmc,wdid')->select();
        foreach ($sfkh as $k => $v) {
            # code...
            $sfkh[$k]["addr"]=db("cg_net")->where(["id"=>$v["wdid"]])->value("detailAddress");
        }
        echo json_encode(['em'=>$em,'qdslxj'=>$qdslxj,'sl_jxs'=>$sl_jxs,'sl_wd'=>$sl_wd,'sl_qdhb'=>$sl_qdhb,'sl_schd'=>$sl_schd,'sl_kq'=>$sl_kq,'ybfkh'=>$ybfkh,'sfkh'=>$sfkh]);
    }

    /**
     * 导购入职申请
     */
    public function dgrzsq(){
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $where = [];
        $data = db('yd_dgrzsq')->where($where)->limit(($page-1)*10,10)->field('xm,sn,status,ctime')->select();
        echo json_encode($data);
    }
    /**
     * 导购入职申请-填写提交
     */
    public function dgrzsqtx(){
        $data = Request::instance()->post();
        $bool = db('yd_dgrzsq')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    /**
     * 导购入职申请详情
     */
    public function dgrzsqxq(){
        $id = $this->request->param('id');
        $data = db('yd_dgrzsq')->where('id',$id)->find();
        echo json_encode($data);
    }
    /**
     * 导购异动申请
     */
    public function dgydsq(){
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $where = [];
        $data = db('yd_dgydsq')->where($where)->limit(($page-1)*10,10)->field('xm,sn,status,ctime')->select();
        echo json_encode($data);
    }
    /**
     * 导购异动申请-填写提交
     */
    public function dgydsqtx(){
        $data = Request::instance()->post();
        $bool = db('yd_dgydsq')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    /**
     * 导购异动申请详情
     */
    public function dgydsqxq(){
        $id = $this->request->param('id');
        $data = db('yd_dgydsq')->where('id',$id)->find();
        echo json_encode($data);
    }

    /**
     * 导购离职申请
     */
    public function dglzsq(){
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $where = [];
        $data = db('yd_dglzsq')->where($where)->limit(($page-1)*10,10)->field('xm,sn,status,ctime')->select();
        echo json_encode($data);
    }
    /**
     * 导购离职申请-填写提交
     */
    public function dglzsqtx(){
        $data = Request::instance()->post();
        $bool = db('yd_dglzsq')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }
    /**
     * 导购离职申请详情
     */
    public function dglzsqxq(){
        $id = $this->request->param('id');
        $data = db('yd_dglzsq')->where('id',$id)->find();
        echo json_encode($data);
    }

    /**
     * 所属导购销量确认
     */
    public function ssdgxlqr(){
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $where = [];
        $data = db('yd_dgxl')->where($where)->limit(($page-1)*10,10)->select();
        echo json_encode($data);
    }

    /**
     * 日程安排查询
     */
    public function rcap(){
        $yue = $this->request->param('yue');
        $userid=$this->request->param('userid');
        $where["cuser"]=$this->geteid($userid);
       $data= db('yd_rcap')->where("ks like '".$yue."%' or js like '".$yue."'")->field("id,lx,ks,js,dd,yq,ctime")->select();
       echo json_encode($data);
    }

    /**
     * 添加日程安排
     */
    public function tjrcap(){
        $data = [];
        $data['lx'] = $this->request->param('lx');
        $data['ks'] = $this->request->param('ks');
        $data['js'] = $this->request->param('js');
        $data['dd'] = $this->request->param('dd');
        $data['yq'] = $this->request->param('yq/a');
        $userid=$this->request->param('userid');
        $data["cuser"]=$this->geteid($userid);
        $data["ctime"]=date("Y-m-d H:i:s");
        $data['yq'] = serialize($data['yq']);
        $bool = db('yd_rcap')->insert($data);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);
        }
    }

    /**
     * 考勤查询
     */
    public function kqcx(){
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $where = [];
        $data = db('yd_kq_log')->where($where)->limit(($page-1)*10,10)->select();
        echo json_encode($data);
    }

    /**
     * 考勤详情
     */
    public function kqcxxq(){
        $id = $this->request->param('id');
        $data = db('yd_kq_log')->where('id',$id)->find();
        echo json_encode($data);
    }

    /**
     * 企业通讯录
     */
    public function qytxl(){
        $xm = $this->request->param('xm');
        $where = [];
        if($xm){
            $where['xm'] = ['like','%'.$xm.'%'];
        }
        $data = db('yd_qytxl')->where($where)->select();
        echo json_encode($data);
    }

    /**
     * 企业通讯录详情
     */
    public function qytxlxq(){
        $id = $this->request->param('id');
        $data = db('yd_qytxl')->where('id',$id)->find();
        echo json_encode($data);
    }

    /**
     * 客户拜访龙虎榜
     */
    public function khbflhb(){
        $year = $this->request->param('year');
        $khq = $this->request->param('khq');
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $where = '';
        if(!$year)
            $year = date('Y');
        $where="rq like '$year%' and bfr is not null ";
        if($khq){
            $row = db('cg_kaoheqi1')->where('id',$khq)->field('starttime,endtime')->find();
            $starttime = date('Y-m-d',$row['starttime']);
            $endtime = date('Y-m-d',$row['endtime']);
            $where .="and rq>='$starttime' and rq<='$endtime' ";
        }
        $data = db('yd_wdbf')->where($where)->group('bfr')->field('count(bfr) cs,bfr')->order('cs desc')->limit(($page-1)*10,10)->select();
        foreach ($data as $k => $v) {
            # code...
            $data[$k]["bfr"]=db("employee")->where("id={$v["bfr"]}")->value("em_name");
        }
        //查询财年和考核期
        $cainian = db('cg_cainian')->where('title',$year)->field("id,title")->find();
        $yjkhq = db('cg_kaoheqi1')->where('cid',$cainian['id'])->field("id,title")->select();
        echo json_encode(['data'=>$data,'cainian'=>$cainian,'yjkhq'=>$yjkhq]);
    }
    public function cainiantokaoheqi(){
        $year = $this->request->param('year');
        $cid=db("cg_cainian")->where(["title"=>$year])->value("id");
        $data=[];
        if($cid){
            $data=db("cg_kaoheqi1")->where(["cid"=>$cid])->field("id,title")->select();
        }
        echo json_encode($data);
    }
    /**
     * 销售进度龙虎榜
     */
    public function xsjdlhb(){
        $year = $this->request->param('year');
        $khq = $this->request->param('khq');
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $where = [];
        if(!$year){
            $year = date('Y');
        }
        $where["type_id"]=1;$where["status"]=7;
        $row = db('cg_cainian')->where('title',$year)->field('starttime,endtime')->find();
            $starttime = $row['starttime'];
            $endtime = $row['endtime'];
        if($khq){
            $row = db('cg_kaoheqi1')->where('id',$khq)->field('starttime,endtime')->find();
            $starttime = $row['starttime'];
            $endtime = $row['endtime'];
            
        }
        $where['sqrq'] = [['>=',$starttime],['<=',$endtime]];
        $data = db('cg_order')->where($where)->group('sqr')->field('count(sqr) cs,sqrmc,sum(yszje) as money')->order('money desc')->limit(($page-1)*10,10)->select();

        //查询财年和考核期
       $cainian = db('cg_cainian')->where('title',$year)->field("id,title")->find();
         $yjkhq = db('cg_kaoheqi1')->where('cid',$cainian['id'])->field("id,title")->select();
        echo json_encode(['data'=>$data,'cainian'=>$cainian,'yjkhq'=>$yjkhq]);
    }
    //客户发货龙虎榜
    public function fhlhb(){
        $year = $this->request->param('year');
        $khq = $this->request->param('khq');
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $where = '';
        if(!$year){
            $year = date('Y');
        }
        $where="fyDate like '$year%' ";
        if($khq){
            $row = db('cg_kaoheqi1')->where('id',$khq)->field('starttime,endtime')->find();
            $starttime = date('Y-m-d',$row['starttime']);
            $endtime = date('Y-m-d',$row['endtime']);
            $where .="and fyDate>='$starttime' and fyDate<='$endtime' ";
        }
        $data=db("bx_fy")->where($where)->group("sdAgency_id")->order('money desc')->field("count(sdAgency_id) as cs,sdAgency,sum(fyZheMoney) as money")->select();
        //查询财年和考核期
        $cainian = db('cg_cainian')->where('title',$year)->field("id,title")->find();
         $yjkhq = db('cg_kaoheqi1')->where('cid',$cainian['id'])->field("id,title")->select();
        echo json_encode(['data'=>$data,'cainian'=>$cainian,'yjkhq'=>$yjkhq]);
    }
    //客户费用龙虎榜
    public function khfylhb(){
        $year = $this->request->param('year');
        $khq = $this->request->param('khq');
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $where = ["t.status"=>7,"t.status2"=>null];
        if(!$year){
            $year = date('Y');
        }
        $row = db('cg_cainian')->where('title',$year)->field('starttime,endtime')->find();
            $starttime = $row['starttime'];
            $endtime = $row['endtime'];
         if($khq){
            $row = db('cg_kaoheqi1')->where('id',$khq)->field('starttime,endtime')->find();
            $starttime = $row['starttime'];
            $endtime = $row['endtime'];
            
        }
        $where['t.ctime'] = [['>=',$starttime],['<=',$endtime]];
        $data=db("cg_ti t")->join("cg_ti_list td","td.ti_id=t.id")->where($where)->group("t.jxs_id")->field("count(t.id) cs,t.jxs_id as jxs,sum(fb_shijitourufeiyong) as money")->order('money desc')->select();
        foreach ($data as $k => $v) {
            # code...
            $data[$k]["jxs"]=db("cg_jxs")->where(["id"=>$v["jxs"]])->value("title");
        }
        //查询财年和考核期
        $cainian = db('cg_cainian')->where('title',$year)->field("id,title")->find();
         $yjkhq = db('cg_kaoheqi1')->where('cid',$cainian['id'])->field("id,title")->select();
        echo json_encode(['data'=>$data,'cainian'=>$cainian,'yjkhq'=>$yjkhq]);
    }
    public function getallfenqu(){
        $data=db("cg_market_zoning")->field("id,title")->select();
        echo json_encode($data);die;
    }
    public function fenqujindu(){
        $fenqu = $this->request->param('fenqu');
        if(!$fenqu){
            $zoning=db("cg_market_zoning")->value("id");
        }
        $data["zid"]=$fenqu;
        $data["ztitle"]=db("cg_market_zoning")->where(["id"=>$fenqu])->value("title");
        $tar=db("target_apply t")->join("target_apply_detail td","td.apply_id=t.id")->where("t.state=7 and t.is_deleted=0 and t.is_actived=1 and t.tag<>1 and t.type_id=1 and fenqu=$fenqu")->sum("td.sale");
        if($tar){
            $data["target"]=round($tar/10000,2);
        }else{
            $data["target"]=0;
        }
        $jxss=db("cg_jxs")->where("zoning=$fenqu")->column("id");
        if($jxss){
            $jxss=implode(',',$jxss);
            $row = db('cg_cainian')->where('title',date("Y"))->field('starttime,endtime')->find();
            $starttime = $row['starttime'];
            $endtime = $row['endtime'];
            $xs=db("cg_ti t")->join("cg_ti_list td","td.ti_id=t.id")->where("t.status=7 and t.status2 is null and t.jxs_id in ($jxss)")->field("fb_shijixiaoliang,totalExpectedSales,yjsjtrfy,fb_shijitourufeiyong")->select();
            $data["yizhi"]=0;
            $data["dacheng"]=0;$yjfy=0;$yjxl=0;
            foreach ($xs as $k => $v) {
                # code...
                if($v["fb_shijixiaoliang"])
                    $data["dacheng"]+=$v["fb_shijixiaoliang"];
                else
                    $data["dacheng"]+=$v["totalExpectedSales"];
                if($v["fb_shijitourufeiyong"])
                    $data["yizhi"]+=$v["fb_shijitourufeiyong"];
                else
                    $data["yizhi"]+=$v["yjsjtrfy"];
                $yjfy+=$v["yjsjtrfy"];
                $yjxl+=$v["totalExpectedSales"];

            }
            $ys=db("yusuan")->where("type=1 and fenqu=$fenqu")->sum("jine");
            if($ys)
                $data["yusuan"]=round($ys/10000,2);
            else
                $data["yusuan"]=0;
            if($data["dacheng"])
                $data["sjfyl"]=$data["yizhi"]/$data["dacheng"]*100;
            else
                $data["sjfyl"]=0;
            if($yjxl)
                $data["yjfyl"]=$yjfy/$yjxl*100;
            else
                $data["yjfyl"]=0;
            $data["dacheng"]=round($data["dacheng"]/10000,2);
            $data["yizhi"]=round($data["yizhi"]/10000,2);
            if($data["target"]){
                $data["xsdcl"]=round($data["dacheng"]/$data["target"],2);
            }else{
                $data["xsdcl"]=0;
            }
            if($data["yusuan"]){
                $data["fysyl"]=round($data["yizhi"]/$data["yusuan"],2);
            }else{
                $data["fysyl"]=0;
            }
        }else{
            $data["dacheng"]=0;
            $data["yusuan"]=0;
            $data["yizhi"]=0;
            $data["yjfyl"]=0;
            $data["sjfyl"]=0;
            $data["xsdcl"]=0;
            $data["fysyl"]=0;
        }
        echo json_encode($data);die;
    }
    /**
     * 所属区域拜访
     */
    public function xsqybf(){
        $start = $this->request->param('start');
        $end = $this->request->param('end');
        $area_type = $this->request->param('area_type');
        if(!$area_type)
            $area_type = 1;
        if($area_type==1){ //经销商拜访
            $where = [];
            if($start&&$end)
                $where['bgrq'] = [['>',$start],['<',$end],'and'];
            elseif($start){
                $where['bgrq'] = ['>',$start];
            }elseif($end){
                $where['bgrq'] = ['<',$end];
            }
            $data = db('yd_jxsbf')->where($where)->select();
            echo json_encode($data);die;
        }elseif($area_type==2){ //网点拜访
            $where = [];
            if($start&&$end)
                $where['rq'] = [['>',$start],['<',$end],'and'];
            elseif($start){
                $where['rq'] = ['>',$start];
            }elseif($end){
                $where['rq'] = ['<',$end];
            }
            $data = db('yd_wdbf')->where($where)->select();
            echo json_encode($data);die;
        }
    }

    /**
     * 消息
     * @return mixed
     */
    public function message(){
       
        $userid = $this->request->param('userid');
        $eid=$this->geteid($userid);
        $where = ["fsr"=>$eid];
//        $where['sjr_id'] = session('employee_id');
        $page = $this->request->param('page')?$this->request->param('page'):1;
       

        $count = db('cg_message')->where($where)->count();
        $data = db('cg_message')->where($where)->order('fssj desc')->limit(($page-1)*10,10)->field("id,fssj,is_read,title")->select();
//        echo db('cg_message')->getLastSql();
        
        foreach($data as $k=>$v){
            $data[$k] = $v;
        }
        echo json_encode($data);
    }

    /**
     * 消息详情
     * @return mixed
     */
    public function messagedetail(){
        $id = $this->request->param('id');

        $data = db('cg_message')->where('id',$id)->find();
        db('cg_message')->where('id',$id)->update(["is_read"=>1]);
        echo json_encode($data);
    }
    //全已读
    public function allyidu(){
        $userid = $this->request->param('userid');
        $eid=$this->geteid($userid);
        $where = ["fsr"=>$eid];
        $bool=db('cg_message')->where($where)->update(["is_read"=>1]);
        
        echo json_encode(['success'=>true,'msg'=>'ok']);
        
    }
    public function areatypes(){
        $data[]=["id"=>1,"title"=>"分区"];
        $data[]=["id"=>2,"title"=>"省份"];
        $data[]=["id"=>3,"title"=>"城市"];
        $data[]=["id"=>4,"title"=>"经销商"];
        echo json_encode($data);
    }
    /*获得二级渠道*/
    public function getchannel2(){
        $data=db("cg_channel_types2")->field("id,title")->select();
        echo json_encode($data);
    }
    
    public function getcustype(){
        $data=db("cg_customertype")->field("id,title")->select();
        echo json_encode($data);
    }
    //渠道费用->市场活动申请->常规
    public function tiapply1(){
        $where = "c.type_id=2  and (c.status2=0 or c.status2 is null) ";
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('cg_ti c')->join("ti_state st","c.status=st.id")->order('c.id desc')->where($where)->limit(($page-1)*10,10)->field("c.id,c.sn,c.title,c.status,st.title as state,c.ctime")->select();
        foreach($data as $k=>$v){

            $data[$k] = $v;
            $data[$k]["ctime"]=date("Y-m-d",$data[$k]["ctime"]);
        }
        echo json_encode(["data"=>$data]);
    }
    //渠道费用->市场活动申请->非常规
    public function tiapply2(){
        $where = "c.type_id=0  and (c.status2=0 or c.status2 is null) ";
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('cg_ti c')->join("ti_state st","c.status=st.id")->order('c.id desc')->where($where)->limit(($page-1)*10,10)->field("c.id,c.sn,c.title,c.status,st.title as state,c.ctime")->select();
        foreach($data as $k=>$v){

            $data[$k] = $v;
            $data[$k]["ctime"]=date("Y-m-d",$data[$k]["ctime"]);
        }
        echo json_encode(["data"=>$data]);
    }
     //渠道费用->市场活动申请->进场
    public function tiapply3(){
        $where = "c.type_id=1 and (c.status2=0 or c.status2 is null) ";
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('cg_ti c')->join("ti_state st","c.status=st.id")->order('c.id desc')->where($where)->limit(($page-1)*10,10)->field("c.id,c.sn,c.title,c.status,st.title as state,c.ctime")->select();
        foreach($data as $k=>$v){

            $data[$k] = $v;
            $data[$k]["ctime"]=date("Y-m-d",$data[$k]["ctime"]);
        }
        echo json_encode(["data"=>$data]);
    }
    //渠道费用->活动执行审核->待审核
    public function ti_daishen(){
        $where = "c.status in (3,4,5,6) and (c.status2=0 or c.status2 is null) ";
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('cg_ti c')->join("ti_state st","c.status=st.id")
        ->join("cg_jxs j","c.jxs_id=j.id")
        ->order('c.id desc')->where($where)->limit(($page-1)*10,10)->field("c.id,c.sn,c.title,c.status,st.title as state,c.ctime,j.addr")->select();
        foreach($data as $k=>$v){

            $data[$k] = $v;
            $data[$k]["ctime"]=date("Y-m-d",$data[$k]["ctime"]);
        }
        echo json_encode(["data"=>$data]);
    }
    //渠道费用->活动执行审核->已审核
    public function ti_yishen(){
        $where = "c.status in (7) and (c.status2=0 or c.status2 is null) ";
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('cg_ti c')->join("ti_state st","c.status=st.id")
        ->join("cg_jxs j","c.jxs_id=j.id")
        ->order('c.id desc')->where($where)->limit(($page-1)*10,10)->field("c.id,c.sn,c.title,c.status,st.title as state,c.ctime,j.addr")->select();
        foreach($data as $k=>$v){

            $data[$k] = $v;
            $data[$k]["ctime"]=date("Y-m-d",$data[$k]["ctime"]);
        }
        echo json_encode(["data"=>$data]);
    }
    //渠道费用->活动执行审核->详情
    public function zhixingmx(){
        $id = $this->request->param('id');
        $ti=db("cg_ti")->where(["id"=>$id])->field("type_id,sn")->find();
        $ti_de=db("cg_ti_list")->where(["ti_id"=>$id])->field("id,net_id,start,end,brand,category,series,sku,product,feetype,sn,tm_id,jxs_id")->select();
        $data=[];
        foreach ($ti_de as $k => $v) {
            # code...
            $tmp=[];
            if($v["net_id"]){
                $cusType="网点";
                $tmp["cusName"]=db("cg_net")->where(["id"=>$v["net_id"]])->value("title");
            }else{
                $cusType="经销商";
                $tmp["cusName"]=db("cg_jxs")->where(["id"=>$v["jxs_id"]])->value("title");
            }
            if($v["product"]||$v["tm_id"]){
                if($v["product"])
                    $p=$v["product"];
                else
                    $p=$v["tm_id"];
                $proType="产品";
                $tmp["pname"]=db("pro_products")->where(["id"=>$p])->value("pro_name");
            }else if($v["sku"]){
                $proType="sku";
                $tmp["pname"]=db("pro_sku")->where(["id"=>$v["sku"]])->value("sku_name");
            }else if($v["series"]){
                $proType="系列";
                $tmp["pname"]=db("pro_series")->where(["id"=>$v["series"]])->value("series_name");
            }else if($v["category"]){
                $proType="品类";
                $tmp["pname"]=db("pro_category")->where(["id"=>$v["category"]])->value("category_name");
            }else{
                $proType="品牌";
                $tmp["pname"]=db("pro_brands")->where(["id"=>$v["brand"]])->value("brand_name");
            }
            //费用类型
            $tmp["feetype"]=db("cg_feiyongkemu3")->where(["id"=>$v["feetype"]])->value("title");
            //活动日期
            $tmp["start"]=date("Y-m-d",$v["start"]);
            $tmp["end"]=date("Y-m-d",$v["end"]);
            //活动编号
            $tmp["bh"]=$ti["sn"]."-".$v["sn"];
            //活动类型
            switch ($ti["type_id"]) {
                case 0:
                    # code...
                    $tmp["type"]="非常规促销";
                    break;
                case 1:
                    # code...
                    $tmp["type"]="进场费用";
                    break;
                case 2:
                    # code...
                    $tmp["type"]="常规促销";
                    break;
            }
            $data[]=$tmp;
        }
        //print_r($ti_de);
        echo json_encode(["data"=>$data]);
    }
    //渠道费用->市场活动反馈->需反馈
    public function ti_needback(){
        $where = "c.status in (7) and (c.status2=0 or c.status2 is null) and c.sfxyfk=1 and c.fb=0";
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('cg_ti c')->join("ti_state st","c.status=st.id")
        ->join("cg_jxs j","c.jxs_id=j.id")
        ->order('c.id desc')->where($where)->limit(($page-1)*10,10)->field("c.id,c.sn,c.title,c.status,st.title as state,c.ctime,j.addr,c.type_id")->select();
        foreach($data as $k=>$v){

            $data[$k] = $v;
            $data[$k]["ctime"]=date("Y-m-d",$data[$k]["ctime"]);
            $data[$k]["statustype"]="已归档";
            switch ($v["type_id"]) {
                case 0:
                    # code...
                    $data[$k]["type"]="非常规促销";
                    break;
                case 1:
                    # code...
                    $data[$k]["type"]="进场费用";
                    break;
                case 2:
                    # code...
                    $data[$k]["type"]="常规促销";
                    break;
            }
            $data[$k]["jine"]=round(db("cg_ti_list")->where(["ti_id"=>$v["id"]])->sum("pizhunweishui"),2);
        }
        echo json_encode(["data"=>$data]);
    }
    //渠道费用->市场活动反馈->已反馈
    public function ti_hasback(){
        $where = "c.status in (7) and (c.status2=0 or c.status2 is null) and c.sfxyfk=1 and c.fb=1";
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = db('cg_ti c')->join("ti_state st","c.status=st.id")
        ->join("cg_jxs j","c.jxs_id=j.id")
        ->order('c.id desc')->where($where)->limit(($page-1)*10,10)->field("c.id,c.sn,c.title,c.status,st.title as state,c.ctime,j.addr,c.type_id")->select();
        foreach($data as $k=>$v){

            $data[$k] = $v;
            $data[$k]["ctime"]=date("Y-m-d",$data[$k]["ctime"]);
            $data[$k]["statustype"]="已归档";
            switch ($v["type_id"]) {
                case 0:
                    # code...
                    $data[$k]["type"]="非常规促销";
                    break;
                case 1:
                    # code...
                    $data[$k]["type"]="进场费用";
                    break;
                case 2:
                    # code...
                    $data[$k]["type"]="常规促销";
                    break;
            }
            $data[$k]["jine"]=round(db("cg_ti_list")->where(["ti_id"=>$v["id"]])->sum("pizhunweishui"),2);
        }
        echo json_encode(["data"=>$data]);
    }
    //渠道费用->市场活动反馈->详情
    public function backdetail(){
        $id = $this->request->param('id');
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $ti=db("cg_ti")->where(["id"=>$id])->field("sn,title,type_id,jxs_id")->find();
        $sn=$ti["sn"];
        $title=$ti["title"];
        switch ($ti["type_id"]) {
            case 0:
            # code...
                $type="非常规促销";
                break;
            case 1:
                # code...
                $type="进场费用";
                break;
            case 2:
                # code...
                $type="常规促销";
                break;
        }
        $jxs=db("cg_jxs")->where(["id"=>$ti["jxs_id"]])->value(["title"]);

        $datas=db("cg_ti_list")->where(["ti_id"=>$id])->field("id,net_id,start,end,brand,category,series,sku,product,feetype,sn,tm_id,pizhunweishui,fb_shijiweishui,totalExpectedSales,fb_shijixiaoliang")->select();
        $data=[];
        foreach ($datas as $k => $v) {
            # code...
            $tmp=[];
            if($v["net_id"]){
               
                $tmp["cusName"]=db("cg_net")->where(["id"=>$v["net_id"]])->value("title");
            }else{
               
                $tmp["cusName"]="";
            }
            if($v["product"]||$v["tm_id"]){
                if($v["product"])
                    $p=$v["product"];
                else
                    $p=$v["tm_id"];
                $tmp["proType"]="产品";
                $tmp["pname"]=db("pro_products")->where(["id"=>$p])->value("pro_name");
            }else if($v["sku"]){
                $tmp["proType"]="sku";
                $tmp["pname"]=db("pro_sku")->where(["id"=>$v["sku"]])->value("sku_name");
            }else if($v["series"]){
                $tmp["proType"]="系列";
                $tmp["pname"]=db("pro_series")->where(["id"=>$v["series"]])->value("series_name");
            }else if($v["category"]){
                $tmp["proType"]="品类";
                $tmp["pname"]=db("pro_category")->where(["id"=>$v["category"]])->value("category_name");
            }else{
                $tmp["proType"]="品牌";
                $tmp["pname"]=db("pro_brands")->where(["id"=>$v["brand"]])->value("brand_name");
            }
            $tmp["start"]=date("Y-m-d",$v["start"]);
            $tmp["end"]=date("Y-m-d",$v["end"]);
            $tmp["pizhunweishui"]=$v["pizhunweishui"];
            $tmp["fb_shijiweishui"]=$v["fb_shijiweishui"];
            $tmp["totalExpectedSales"]=$v["totalExpectedSales"];
            $tmp["fb_shijixiaoliang"]=$v["fb_shijixiaoliang"];
        }
    }

}